在 Scott Meyers 的《Effective Modern C++》中,他写道:
It's worth nothing that because
std::mutex
is a move-only type (i.e., a type that can be moved, but not copied), a side effect of addingm
toPolynomial
is thatPolynomial
loses the ability to be copied. It can still be moved, however.
在这里,他将一个 std::mutex m
作为成员变量添加到类 Polynomial
中,以解释为什么应该保护对 const 成员变量的访问一个类(多线程时)。我理解了他解释的概念。但我需要更多解释的一件事是“为什么向类添加仅移动类型会使该类作为仅移动类型不可复制”?为什么像 std::mutex
这样的类型默认情况下, std::atomic
是仅移动类型?如果我们想要执行复制操作,即使在我们的类中添加了仅移动类型的变量,我们该如何解决这个问题?
最佳答案
"why Adding a move only type to a class makes that class as move only type not copy-able"
这并不完全正确。添加不可复制的成员变量可以防止您编写类似 Type (const Type& t) = default;
的内容,但您仍然可以实现自己的复制构造函数,该构造函数会忽略不可复制的成员
class Type{
int integer;
std::mutex m;
public:
Type() = default;
Type(const Type& rhs): integer (rhs.integer){}
}
除此之外,您还可以找到许多包含仅移动成员的对象示例,但它们本身是不可移动的,仅仅是因为开发人员删除了移动构造函数。
why types like std::mutex and std::atomic is move only type by default?
它们都没有实现移动构造函数。这是错误的说法。
关于c++ - 向类添加仅移动类型会使该类成为仅移动类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36284938/