已删除的函数 (C++11)

已删除函数 声明是引入到 C++11 标准中的新函数声明形式。 要将函数声明为已删除的函数,可以将 =delete; 说明符附加到该函数声明的末尾。 编译器将禁用已删除函数的用法。

如果要阻止使用隐式定义的函数,那么可以将该函数声明为已删除的函数。 例如,您可以将隐式定义的类的复制赋值运算符和复制构造函数声明为已删除的函数,以防止该类的对象副本。
class A{    
public:
  A(int x) : m(x) {}
  A& operator = (const A &) = delete;  // Declare the copy assignment operator
                                       // as a deleted function.
  A(const A&) = delete;                // Declare the copy constructor
                                       // as a deleted function.

private:
  int m;
};

int main(){
  A a1(1), a2(2), a3(3);
  a1 = a2;     // Error, the usage of the copy assignment operator is disabled.
  a3 = A(a2);  // Error, the usage of the copy constructor is disabled.
}
您还可以通过将不期望的转换构造函数和运算符声明为已删除的函数来防止有问题的转换。 以下示例显示了如何防止从 double 到类类型的不期望的转换。
class B{
public:
  B(int){}                
  B(double) = delete;  // Declare the conversioin constructor as a deleted function
};

int main(){
  B b1(1);        
  B b2(100.1);         // Error, conversion from double to class B is disabled.
}
已删除的函数隐式内联。 删除的函数定义必须是函数的第一个声明。 例如:
class C {
public:  
  C();
};

C::C() = delete;  // Error, the deleted definition of function C must be
                  // the first declaration of the function.