对类中的方法正确使用`= delete`

| 以下代码片段是否正确地为一个类取消定义了所有其他生成的方法和构造函数?
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?
};
这会删除每个默认的编译器实现,只保留析构函数,对吗?如果没有它,该类将(几乎)无法使用,但是我也可以删除它,对吗? 移动分配-2ѭ的返回类型
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;
};
复制构造函数的显式声明禁止隐式生成默认构造函数,移动构造函数和移动分配成员。明确删除这些成员是一种喜好。有些人可能会认为它是很好的文档。其他人可能认为它过于冗长。     
对我来说似乎很好。即使对象是由右值引用构造的,返回值
operator=
也必须是常规引用。那是因为您不能只将一个左值(ѭ6comp)编译为一个右值。 并且它应该使用每个非常量
Picture& operator=(Picture&&)
的右值引用。您将如何从一个恒定的物体移动? ;)     

要回复问题请先登录注册