在阅读Bjarne Stroustrup的CoreCppGuidelines时,我找到了一条与我的经历相矛盾的指南.
该C.21要求如下:
如果您定义或
=delete任何默认操作,请定义或=delete全部
原因如下:
特殊函数的语义密切相关,因此如果需要非默认函数,则其他人也需要修改.
根据我的经验,重新定义默认操作的两种最常见情况如下:
#1:使用默认主体定义虚拟析构函数以允许继承:
class C1
{
...
virtual ~C1() = default;
}
Run Code Online (Sandbox Code Playgroud)
#2:默认构造函数的定义,对RAII类型的成员进行一些初始化:
class C2
{
public:
int a; float b; std::string c; std::unique_ptr<int> x;
C2() : a(0), b(1), c("2"), x(std::make_unique<int>(5))
{}
}
Run Code Online (Sandbox Code Playgroud)
根据我的经验,所有其他情况都很少见.
您如何看待这些例子?它们是C.21规则的例外,还是最好在这里定义所有默认操作?还有其他常见的例外吗?
这是一个演示类.我不希望我的类被复制,所以我删除了复制构造函数.我希望vector.emplace_back使用这个构造函数'MyClass(Type type)'.但这些代码不会编译.为什么?
class MyClass
{
public:
typedef enum
{
e1,
e2
} Type;
private:
Type _type;
MyClass(const MyClass& other) = delete; // no copy
public:
MyClass(): _type(e1) {};
MyClass(Type type): _type(type) { /* the constructor I wanted. */ };
};
std::vector<MyClass> list;
list.emplace_back(MyClass::e1);
list.emplace_back(MyClass::e2);
Run Code Online (Sandbox Code Playgroud)