博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Effective C++条款16:成对使用new和delete时要采取相同形式
阅读量:4223 次
发布时间:2019-05-26

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

Scott Meyers说:成对使用new和delete时要采取相同形式。 意思很简单, 但我们程序员应该非常小心, 尤其是在处理堆内存问题的时候。 new和delete使用不恰当, 会产生未定义的不明确行为。 比如, 如下方式就是很好的方式:

[cpp] 
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. int main()  
  5. {  
  6.     int *p = new int;  
  7.     delete p; // 此时不能有[]  
  8.     p = NULL;  
  9.   
  10.     p = new int[4];  
  11.     delete []p; // 此时必须有[]  
  12.     p = NULL;  
  13.   
  14.     return 0;  
  15. }  

       但是, 有一种隐蔽的错误, 如:

[cpp] 
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. typedef int intArr[100];  
  5.   
  6.   
  7.   
  8. // ...  
  9.   
  10.   
  11.   
  12. int main()  
  13. {  
  14.     int *p = new intArr;  
  15.     delete p; //错误, 会产生不明确的未定义行为  
  16.     p = NULL;  
  17.   
  18.     return 0;  
  19. }  
       应该采用:

[cpp] 
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. typedef int intArr[100];  
  5.   
  6.   
  7.   
  8. // ...  
  9.   
  10.   
  11.   
  12. int main()  
  13. {  
  14.     int *p = new intArr;  
  15.     delete []p; // 必须用[]  
  16.     p = NULL;  
  17.   
  18.     return 0;  
  19. }  

       为了避免第二个程序中的错误, Scott Meyers建议最好不要对数组采用typedef定义。

链接:http://blog.csdn.net/stpeace/article/details/46574847

你可能感兴趣的文章
Docker拉取镜像失败报错Error response from daemon: Get https://registry-1.docker.io解决办法
查看>>
IO操作的工具类总结
查看>>
Java中如何遍历Map对象的4种方法
查看>>
图片延时加载例子详解
查看>>
js获取url参数值的两种方式详解
查看>>
MyEclipse设置默认注释的格式
查看>>
同一服务器部署多个tomcat时的端口号修改详情
查看>>
常用正则表达式集锦
查看>>
Spring定时器的时间表达式
查看>>
主键和唯一索引的区别
查看>>
linux下使用yum安装gcc详解
查看>>
aclocal安装依赖的库
查看>>
ERROR 1045 (28000): Access denied for user root@localhost (using password: NO)解决方案
查看>>
Host 'XXX' is not allowed to connect to this MySQL server解决方案
查看>>
corosync pacemaker 配置高可用集群(一)
查看>>
nginx(一) nginx详解
查看>>
nginx(二) nginx编译安装 及 配置WEB服务
查看>>
nginx(三) nginx配置:反向代理 负载均衡 后端健康检查 缓存
查看>>
jQuery核心--多库共存
查看>>
6 51点亮第一个LED
查看>>