我正在研究 C++ 中的多线程,我编写了一个简单的类,其中包含一个私有(private) std::mutex
对象,用于在调用成员函数时进行同步:
#include <mutex>
#include <iostream>
class SynchClass
{
public:
SynchClass() {}
void inline SynchronizedInterfaceFunction();
private:
std::mutex mMutex;
};
void inline SynchClass::SynchronizedInterfaceFunction()
{
std::lock_guard<std::mutex> lock(mMutex);
for (int i = 0; i < 10; i++)
std::cout << "thread n: " << std::this_thread::get_id() << " inside function" << std::endl;
std::cout << std::endl;
}
现在,我这个函数有一个删除复制构造函数和复制赋值运算符,因为 std::mutex 可以 move 但不能复制/赋值。
因此,我为该类提供了一个 move 构造函数(编译器不会自动生成):
class SynchClass
{
public:
// ... other members as before
SynchClass(SynchClass &&rhs) : mMutex(std::move(rhs.mMutex)) {}
};
但是当我添加此行时,编译器提示我正在尝试调用 std::mutex
的已删除复制构造函数:
In file included from main.cpp:5:0:
SynchClass.h: In constructor 'SynchClass::SynchClass(SynchClass&&)':
SynchClass.h:8:61: error: use of deleted function 'std::mutex::mutex(const std::mutex&)'
SynchClass(SynchClass &&rhs) : mMutex(std::move(rhs.mMutex)) {}
^
In file included from C:/Program Files/mingw64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/mutex:43:0,
from main.cpp:2:
C:/Program Files/mingw64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/bits/std_mutex.h:97:5: note: declared here
mutex(const mutex&) = delete;
但我使用 std::move
将左值转换为右值,因此应该调用 std::mutex 的 move 构造函数。
我错过了什么?
最佳答案
std::mutex
不可复制且不可 move 。它没有 move 构造函数或赋值。 mutex
的库要求:
33.4.3.2 Mutex types [thread.mutex.requirements.mutex]
3 The mutex types shall be DefaultConstructible and Destructible . If initialization of an object of a mutex type fails, an exception of type system_error shall be thrown. The mutex types shall not be copyable or movable.
如果你想让你的类 move 可构造,那么你需要在某个时候添加另一层间接层,例如使用std::unique_ptr<std::mutex>
.
关于c++ - 使用 move 语义在构造函数中初始化类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55775182/