=default/=delete
• 当我们声明有参构造函数时,编
译器就不会创建默认构造函数。
• 特殊成员函数包括:
➢ 默认构造函数
➢ 析构函数
➢ 复制构造函数
➢ 等
非特殊成员函数不能默认
=delete
1.禁用成员函数的使用。这是通过附加= delete来完成的; 说明符到该函数声明的结尾。
2.使用场景
禁用拷贝构造函数:
// copy-constructor using delete operator
#include <iostream>
using namespace std;
class A {
public:
A(int x): m(x) { }
// Delete the copy constructor
A(const A&) = delete;
// Delete the copy assignment operator
A& operator=(const A&) = delete;
int m;
};
int main() {
A a1(1), a2(2), a3(3);
// Error, the usage of the copy assignment operator is disabled
a1 = a2;
// Error, the usage of the copy constructor is disabled
a3 = A(a2);
return 0;
}
禁用不需要的参数转换
// type conversion using delete operator
#include <iostream>
using namespace std;
class A {
public:
A(int) {}
// Declare the conversion constructor as a deleted function. Without this step,
// even though A(double) isn't defined, the A(int) would accept any double value
// for it's argumentand convert it to an int
A(double) = delete;
};
int main() {
A A1(1);
// Error, conversion from double to class A is disabled.
A A2(100.1);
return 0;
}
请注意,删除的函数是隐式内联的,这一点非常重要。删除的函数定义必须是函数的第一个声明。换句话说,以下方法是将函数声明为已删除的正确方法:
class C {
public:
C(C& a) = delete;
};
但是以下尝试声明删除函数的方法会产生错误:
// incorrect syntax of declaring a member function as deleted
class C {
public:
C();
};
// Error, the deleted definition of function C must be the first declaration of the function.
C::C() = delete;
明确删除函数有什么好处?
删除特殊成员函数提供了一种更简洁的方法来防止编译器生成我们不想要的特殊成员函数。(如“禁用拷贝构造函数”示例中所示)。
删除正常成员函数或非成员函数可防止有问题的类型导致调用非预期函数(如“禁用不需要的参数转换”示例中所示)。