博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++11的delete
阅读量:4093 次
发布时间:2019-05-25

本文共 1659 字,大约阅读时间需要 5 分钟。

一、介绍

在C ++ 11之前,操作符delete 只有一个目的,即释放已动态分配的内存。而C ++ 11标准引入了此操作符的另一种用法,即:禁用成员函数的使用。这是通过附加= delete来完成的; 说明符到该函数声明的结尾。

使用’= delete’说明符禁用其使用的任何成员函数称为expicitly deleted函数。

虽然不限于它们,但这通常是针对隐式函数

二、实例

禁用拷贝构造函数:

// copy-constructor using delete operator #include 
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 
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 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/

你可能感兴趣的文章
单例模式,你会写几种?
查看>>
数据分析 第六篇:同期群分析
查看>>
Liquibase 使用(全)
查看>>
一篇长文说 git 基础
查看>>
rest_framework框架之认证功能的使用和源码实现流程分析
查看>>
JAVA8 之初识函数式编程与函数式接口(一)
查看>>
【测话杂谈】我的2019—年度总结
查看>>
利用Redis实现集群或开发环境下SnowFlake自动配置机器号
查看>>
MYSQL调优实战
查看>>
TypeScript躬行记(8)——装饰器
查看>>
利用Redis实现集群或开发环境下SnowFlake自动配置机器号
查看>>
node多进程的创建与守护
查看>>
react-native-swiper使用的坑
查看>>
BeetleX之XRPC使用详解
查看>>
Kerrigan:配置中心管理UI的实现思路和技术细节
查看>>
Python综合应用:教你用字符打印一张怀旧风格的照片
查看>>
Cocos Creator | 飞刀大乱斗开发教程系列(一)
查看>>
abp(net core)+easyui+efcore实现仓储管理系统——ABP WebAPI与EasyUI结合增删改查之七(三十三)
查看>>
做为一个菜鸡的2019年总结
查看>>
spring注解之@Import注解的三种使用方式
查看>>