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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…