返回值复制操作是在lock_guard析构函数之前还是之后执行的? [英] Is a copy-on-return operation executed prior or after lock_guard destructor?
问题描述
get_a()
函数在竞争条件下是否安全?还是需要显式复制 str _
? get_b()
以便具有线程安全功能?
Is the get_a()
function safe for race-conditions or do I need to explicitly copy str_
as in get_b()
in order to have a thread-safe function?
class Class {
public:
auto get_a() -> std::string {
auto&& guard = std::lock_guard{mutex_};
return str_;
}
auto get_b() -> std::string {
auto&& guard = std::lock_guard{mutex_};
auto str = str_;
return str;
}
private:
std::mutex mutex_{};
std::string str_{};
};
注意:我知道堆栈溢出有类似的问题,但是我
推荐答案
调用结果的复制初始化在
return
语句的操作数建立的全表达式结束时,在临时变量销毁之前进行排序。依次在破坏return
语句的块的局部变量之前进行排序。
The copy-initialization of the result of the call is sequenced before the destruction of temporaries at the end of the full-expression established by the operand of the
return
statement, which, in turn, is sequenced before the destruction of local variables of the block enclosing thereturn
statement.
这意味着以下顺序发生:
This means that the following happen in order:
- 返回对象已被复制初始化
- return语句中的任何临时对象都将被破坏
- 局部变量将被破坏
因此,我们可以推断 get_a
是完全安全的。
So, we can infer that get_a
is completely safe.
这篇关于返回值复制操作是在lock_guard析构函数之前还是之后执行的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!