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 astd::lock_guardand vice versa. So I changed the two branches to the same type, herestd::unique_lock<std::mutex>because lock_guard isn't designed be used without a valid mutex. But still preferstd::lock_guardoverstd::unique_lockin 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
lockScopewould only have existed in one branch.

Add a Comment
Comments are closed.