c++ - 返回时复制操作是在 lock_guard 析构函数之前还是之后执行的?

标签 c++ thread-safety destructor race-condition stdmutex

get_a() 函数对于竞争条件是否安全,或者我是否需要像在 get_b() 中那样显式复制 str_ 以便按顺序有一个线程安全的功能?

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_{};
};

注意:我知道 Stack Overflow 上有类似的问题,但我找不到明确回答这个问题的问题。

最佳答案

[stmt.return]p3 :

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 the return statement.

这意味着以下顺序发生:

  1. 返回对象是复制初始化的
  2. return 语句中的任何临时对象都被销毁
  3. 局部变量被销毁

因此,我们可以推断get_a 是完全安全的。

关于c++ - 返回时复制操作是在 lock_guard 析构函数之前还是之后执行的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53613641/

相关文章:

python - Django 和线程安全

c++ - 函数参数不调用构造函数?

c++ - std::end 以 char 的原始数组结尾

c# - 调用 Task.Result 时出现 ThreadAbortException

与当前对象相关的 C++ 指针和地址说明

C#,有没有 "thread-safe"流这样的东西?

c++ - 在 scoped_ptr 出现异常时不调用析构函数

c++ - 破坏空指针时的访问冲突

c++ - 作为类(class)成员 "variable"发挥作用

c++ - 括号是否强制评估顺序并定义未定义的表达式?