对于取消定义类的所有其他生成的方法和构造函数,以下代码片段是否正确?
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?
};这会删除所有默认的编译器实现,只留下析构函数,对吧?如果没有它,我想这个类将(几乎)无法使用,但我也可以删除它,对吗?
move-assign operator=(Picture&&)的返回类型Picture&是否正确?如果我为返回类型写Picture&&会有什么不同吗?
发布于 2011-04-16 23:32:16
除了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;
};复制构造函数的显式声明禁止隐式生成默认构造函数、移动构造函数和移动赋值成员。显式删除这些成员是个人喜好问题。有些人可能会认为它是很好的文档。其他人可能会认为它过于冗长。
发布于 2011-04-16 22:23:24
我觉得挺好的。operator= 的返回值必须为正常引用,即使对象是从引用构造的。这是因为您不能只将左值(*this)编译为右值。
并且它应该接受每个非常数Picture& operator=(Picture&&)的右值引用。如何从常量对象中移动?;)
https://stackoverflow.com/questions/5687055
复制相似问题