Quick Q: Conditional use of std::lock_guard

Quick A: Use std::unique_lock instead.

Recently on SO:

Conditional use of std::lock_guard

How about this one?

void bar(std::mutex * optionalMutex = nullptr)
{
        auto lockScope = (optionalMutex == nullptr) ?
                           std::unique_lock<std::mutex>()
                         : std::unique_lock<std::mutex>(*optionalMutex);

}

Explanation: You're compiler had trouble with your prior statement because, you can not suddenly change the type of the ternary ? expression, i.e. the literal 0 is not a std::lock_guard and vice versa. So I changed the two branches to the same type, here std::unique_lock<std::mutex> because lock_guard isn't designed be used without a valid mutex. But still prefer std::lock_guard over std::unique_lock in the simpler cases, because it will make you code more readable.

Also your statement wasn't viable for the compiler, i.e. even syntactical correct, because the variable lockScope would only have existed in one branch.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.