正确使用类中的方法' = delete '
Correct use of `= delete` for methods in classes
下面的代码片段对于不定义所有其他生成的类方法和构造函数是正确的吗?
struct Picture {
// 'explicit': no accidental cast from string to Picture
explicit Picture(const string &filename) { /* load image from file */ }
// no accidental construction, i.e. temporaries and the like
Picture() = delete;
// no copy
Picture(const Picture&) = delete;
// no assign
Picture& operator=(const Picture&) = delete;
// no move
Picture(Picture&&) = delete;
// no move-assign
Picture& operator=(Picture&&) = delete; // return type correct?
};
这删除了每个默认的编译器实现,只留下析构函数,对吗?如果没有它,类将(几乎)无法使用,我猜,但我也可以删除它,对吗?
移动分配operator=(Picture&&)
的返回类型Picture&
是否正确?如果我为返回类型写Picture&&
会有什么不同吗?
除了Xeo的回答:
是的,一切都是正确的。如果您愿意,可以删除所有已删除的成员,但删除的复制构造函数和删除的拷贝赋值,并具有相同的效果:
struct Picture { // Also ok
// 'explicit': no accidental cast from string to Picture
explicit Picture(const string &filename) { /* load image from file */ }
// no copy
Picture(const Picture&) = delete;
// no assign
Picture& operator=(const Picture&) = delete;
};
复制构造函数的显式声明禁止隐式生成默认构造函数、move构造函数和move赋值成员。是否显式删除这些成员取决于个人喜好。有些人可能会认为这是很好的文档。其他人可能会认为它过于啰嗦。
我觉得很好。operator=
的返回值必须是一个正常的引用,即使对象是从右值引用构造的。这是因为不能将左值(*this
)编译为右值。
它应该为每个非const Picture& operator=(Picture&&)
取右值引用。你如何从一个不变的物体移动?div;)
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 为多线程环境包装 c++ new/delete 的安全/好方法
- 虚拟方法在 C++0x 中不能"delete"吗?
- 编写没有new和delete关键字的c++?最佳方法
- 当导入swig生成的模块时,Python会报错缺少delete方法
- 正确使用类中的方法' = delete '