Is a copy-on-return operation executed prior or after lock_guard destructor? [duplicate]

 ̄綄美尐妖づ 提交于 2020-07-15 04:36:48

问题


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

Note: I'm aware that there are similar questions here on Stack Overflow, but I could not find one which explicitly answers this question.


回答1:


[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.

This means that the following happen in order:

  1. The return object is copy-initialized
  2. Any temporaries inside the return statement are destroyed
  3. Local variables are destroyed

So, we can infer that get_a is completely safe.



来源:https://stackoverflow.com/questions/53613641/is-a-copy-on-return-operation-executed-prior-or-after-lock-guard-destructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!