基于作用域的锁守卫和返回值的时间安排 [英] Timing of scope-based lock guards and return values

查看:18
本文介绍了基于作用域的锁守卫和返回值的时间安排的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class C {
    mutable std::mutex _lock;
    map<string,string> deep_member;
public:
    auto get_big_lump()
     {
     std::unique_lock<std::mutex> lock(_lock); // establish scope guard
     return deep_member;  // copy the stuff while it can't be changed on another thread.
     }
};

关于守卫和复制返回值的保证时间是多少?复制是否会在持有锁时进行,或者在允许(或实际!)优化的情况下,是否可以在函数体返回后进行一些复制?

What is the guaranteed timing with respect to the guard and the copying of the return value? Will the copy take place while the lock is held, or can some of it be done after the function body returns, in the case of allowed (or actual!) optimizations?

推荐答案

局部对象的所有析构函数都在函数体终止后调用.return 语句是函数体的一部分,因此可以保证在执行复制时保持锁定.

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.

但是,请记住代码中的实际作用域锁定是不正确的.您需要 lock_guard - 但它可能只是一个演示复制粘贴错误,而真正的代码有真正的保护.

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.

这篇关于基于作用域的锁守卫和返回值的时间安排的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆