Effective C++条款16:成对使用new和delete时要采取相同形式


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

[cpp]  view plain copy
  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]  view plain copy
  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]  view plain copy
  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.youkuaiyun.com/stpeace/article/details/46574847




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值