对于以互斥作为成员的类,当我创建复制构造函数时,我需要决定锁定哪个互斥。对于下面的代码,我想知道为什么我只需要锁定rhs.mu_而不必锁定this->mu_?是否有可能多个线程为同一个对象调用复制构造函数?
class Obj {
public:
std::mutex mu_;
std::string data_;
// copy ctor
Obj(const Obj& rhs) {
std::unique_lock<std::mutex> lk(rhs.mu_); // why only lock rhs.mu_?
data_ = rhs.data_;
}
}
更新: 这段代码是否在使用new的同时调用了copy ctor?
Obj* t = nullptr;
Obj someObj;
// ... populate someObj
std::thread t1([&]() { t = new Obj(someObj); });
std::thread t2([&]() { t = new Obj(someObj); });
最佳答案
如果你的变量是局部变量,在构造过程中其他线程无法访问它,因为其他线程不能命名本线程中的局部变量。
如果您的变量具有静态生命周期,则线程安全由 C++ 标准保证:
Dynamic initialization of a block-scope variable with static storage duration or thread storage duration is performed the first time control passes through its declaration;
...
If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.
因此构造函数不会被调用两次。
关于c++ - 复制带有互斥量的 ctor 作为数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48576514/