本文共 1659 字,大约阅读时间需要 5 分钟。
在C ++ 11之前,操作符delete 只有一个目的,即释放已动态分配的内存。而C ++ 11标准引入了此操作符的另一种用法,即:禁用成员函数的使用。这是通过附加= delete来完成的; 说明符到该函数声明的结尾。
使用’= delete’说明符禁用其使用的任何成员函数称为expicitly deleted函数。
虽然不限于它们,但这通常是针对隐式函数
禁用拷贝构造函数:
// copy-constructor using delete operator #includeusing 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 #includeusing 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 noncopyable {protected: noncopyable() {} ~noncopyable() {}private: //禁止拷贝 noncopyable(const noncopyable &that) = delete; noncopyable(noncopyable &&that) = delete; noncopyable &operator=(const noncopyable &that) = delete; noncopyable &operator=(noncopyable &&that) = delete;};
最后,明确删除函数有什么好处?
删除特殊成员函数提供了一种更简洁的方法来防止编译器生成我们不想要的特殊成员函数。(如“禁用拷贝构造函数”示例中所示)。 删除正常成员函数或非成员函数可防止有问题的类型导致调用非预期函数(如“禁用不需要的参数转换”示例中所示)。参考:
转载地址:http://qjiii.baihongyu.com/