c++ - 向类添加仅移动类型会使该类成为仅移动类型?

标签 c++ c++11 mutex c++14 stdatomic

在 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 adding m to Polynomial is that Polynomial 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/

相关文章:

c++ - std::mutex 是否可以轻易破坏?

c# - 将 C/C++ 函数导入 C#

c++ - 调试 Visual C++ 复杂项目

c++ - 模板函数中的 std::function

c++ - 使用辅助函数 (c++) 定义运行时已知的全局常量变量

c++ - 这段代码是线程安全的吗?

c++ - 带有互斥锁和事件的 WaitForMultipleObjects

c++ - 在 C++ 中将 lower_bound() 与一组对象一起使用

c++ - 如何在类定义之外的模板类中定义模板函数?

c++ - 读取 cmd 生成的文件,结果出现 3 个奇怪的符号