Timing of scope-based lock guards and return values

前端 未结 2 818
一向
一向 2020-12-20 23:44
class C {
    mutable std::mutex _lock;
    map deep_member;
public:
    auto get_big_lump()
     {
     std::unique_lock lock         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-21 00:03

    std::lock does not establish a scope guard! It only locks. It does not unlock. You want this:

    std::unique_lock 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.

提交回复
热议问题