类中方法的正确使用`=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?
};
这会删除每个默认编译器实现,只留下析构函数,对吗?我想如果没有它,该类将(几乎)无法使用,但我也可以删除它,对吗?
move-assign operator=(Picture&&)
的返回类型 Picture&
是否正确?如果我为返回类型编写 Picture&&
会有什么不同吗?
Is the following snipplet correct for un-defining all otherwise generated methods and constructors for a class?
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?
};
This deletes every default compiler implementation and only leaves the destructor, right? Without it the class would be (almost) unusable I guess, but I could delete it as well, correct?
Is the return type Picture&
of the move-assign operator=(Picture&&)
correct? Does it make a difference if I wrote Picture&&
for the return type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除了Xeo的回答:
是的,一切都是正确的。如果您愿意,可以消除除删除的复制构造函数和删除的复制赋值之外的所有已删除成员,并具有相同的效果:
复制构造函数的显式声明会禁止默认构造函数、移动构造函数和移动赋值成员的隐式生成。明确删除这些成员是一个品味问题。有些人可能会认为它是很好的文档。其他人可能会认为它过于冗长。
In addition to Xeo's answer:
Yes, everything is correct. If you wanted you could eliminate all of the deleted members but the deleted copy constructor and deleted copy assignment and have the same effect:
The explicit declaration of the copy constructor inhibits the implicit generation of the default constructor, move constructor and move assignment members. Having these members explicitly deleted is a matter of taste. Some will probably see it as good documentation. Others may see it as overly verbose.
对我来说似乎不错。
operator=
的返回值必须是普通引用,即使该对象是从右值引用构造的。这是因为您不能仅将左值 (*this
) 编译为右值。它应该采用每个非常量
Picture& 的右值引用。运算符=(图片&&)
。你会如何摆脱一个恒定的物体? ;)Seems fine to me. The return value of
operator=
must be a normal reference, even if the object is constructed from a rvalue reference. That is because you can't just compile an lvalue (*this
) to an rvalue.And it should take that rvalue reference per non-const
Picture& operator=(Picture&&)
. How would you move from a constant object? ;)