=default/=delete

=default/=delete
C++11允许添加“=default” 说明符 到函数声明的末尾,以将该函数声明为显示默认构造函数。这就使得编译器为显示默认函数生成了默认实现,它比手动编程函数更加有效。
• 当我们声明有参构造函数时,编 译器就不会创建默认构造函数。
• 特殊成员函数包括:
➢ 默认构造函数
➢ 析构函数
➢ 复制构造函数
➢ 等
非特殊成员函数不能默认
=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;  
明确删除函数有什么好处?
删除特殊成员函数提供了一种更简洁的方法来防止编译器生成我们不想要的特殊成员函数。(如“禁用拷贝构造函数”示例中所示)。
删除正常成员函数或非成员函数可防止有问题的类型导致调用非预期函数(如“禁用不需要的参数转换”示例中所示)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值