Timing of scope-based lock guards and return values
All destructor of local objects are called after the function body terminates. Return statement is a part of a function body, so it is guaranteed the lock will be held while the copy is performed.
Optimizations will not change this fact, they will only change the destination for the copy - it could either be an intermediate temporary or the real destination on the call site. The lock will only exist for the first copy, no matter where it is being sent to.
However, please keep in mind the the actual scope lock in the code is not correct. You need lock_guard
- but it is possible it is simply a demo copy-paste error and real code has real guard in place.
std::lock
does not establish a scope guard! It only locks. It does not unlock. You want this:
std::unique_lock<std::mutex> lock(_lock);
which locks on construction and unlocks on destruction (which occurs on scope exit).
The initialization of the return value will occur before local variables are destroyed, and hence while the lock is held. Compiler optimizations are not allowed to break correctly synchronized code.
However, note that if the return value is then copied or moved into some other variable, this second copy or move will occur after the lock is released.