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: Your 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 your 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.


What you really have is two functions, one that locks, and one that doesn't. The first one can call the second:

void bar() {
    // whatever
}

void bar(std::mutex* mtx) {
    std::lock_guard<std::mutex> lockScope(*mtx);
    bar();
}

I have only this solution. Using a dummy mutex object:

The code is:

bar( std::mutex * optionalMutex = nullptr )
{
   ...
   std::mutex dummyMutex;
   std::lock_guard<std::mutex> lockScope( optionalMutex ? *optionalMutex, dummyMutex );

   foo...     <- NOW foo is protected when optionalMutex was provided
}