Timing of scope-based lock guards and return values(基于作用域的锁守卫和返回值的时间安排)
问题描述
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.
这篇关于基于作用域的锁守卫和返回值的时间安排的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:基于作用域的锁守卫和返回值的时间安排
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01