Effective C++ 条款16
来源:互联网 发布:游泳馆软件 编辑:程序博客网 时间:2024/05/16 23:38
成对使用new和delete时要采取相同形式
本节条款知识点在于delete和delete[]的区别
大家都知道在new一个对象的时候要delete一个对象,在new 一个对象数组时要delete[]才是正确的。
大家也知道new产生两个行为,一个是申请对象所需内存,另一个是调用类构造函数初始化对象。
那么,delete的行为也有两个,一个是调用对象的析构函数,另一个是回收内存。
而new[]是对每个对象都进行上面同样的行为。
这时候如果不小心new匹配了delete[],或者new[]匹配了delete,会出现什么问题呢?
#include<iostream>#include<string>using namespace std;int main(){ string *s1 =new string[5] ; string *s2 = new string("mmm"); delete s1;//错误,程序崩溃 delete[]s2;//错误,程序崩溃 return 0;}
如果匹配错误,程序会出现未定义错误。
所以,总结一句,用new就配delete。用new[]就匹配delete[]。
1 0
- 《Effective C++》资源管理:条款16-条款17
- Effective C++:条款01
- Effective C++:条款02
- Effective C++:条款03
- Effective C++:条款04
- Effective C++:条款05
- Effective C++:条款06
- Effective C++:条款07
- Effective C++:条款08
- 《effective C++》条款三
- 《effective C++》条款5
- 《effective C++》条款六
- Effective C++--经验条款
- Effective C ++ 条款34
- 《Effective C++》条款05
- 《Effective C++》条款06
- 《Effective C++》条款08
- 《Effective C++》资源管理:条款13-条款15
- 苹果:Apple Watch心率随机读取是功能不是Bug
- java中的json
- 修改aix /etc/profile
- BenOS实时操作系统解密
- 详解10种解决启动故障的方法
- Effective C++ 条款16
- Spring IOC体验之—如何依赖注入
- AIX下exp的query写法
- UIButton上的图片和文字位置调整
- 一个数组中有30个数(随机产生[0,30]),将数组中重复的数字去除,动态创建数组保存剩下的数字
- Repository(字典树,避免重复计数)
- 安卓5.1自带浏览器主页设置–转载
- [php] Thinkphp实现上一篇下一篇及跳转分页代码
- SAP项目失败案例