基于范围的锁保护和返回值的时间 [英] Timing of scope-based lock guards and return values

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

问题描述

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天全站免登陆