在类中的方法正确使用`= delete` [英] Correct use of `= delete` for methods in classes
问题描述
下面的snipplet是否适用于取消定义一个类的所有其他方法和构造函数?
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?
是返回类型 Picture&
是否正确? operator =(Picture&&)
的
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?
推荐答案
除了Xeo的回答:
是的,一切都是正确的。如果你想要,你可以消除所有删除的成员,但删除的副本构造函数和删除的副本分配,并具有相同的效果:
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:
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 constructor和move assignment成员。将这些成员明确删除是一个问题。有些人可能会看到它是好的文档。其他人可能会认为它过于冗长。
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.
这篇关于在类中的方法正确使用`= delete`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!