delete delete[]

http://stackoverflow.com/questions/4255598/delete-vs-delete

From the standard (5.3.5/2) :

In the first alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object or a pointer to a sub-object (1.8) representing a base class of such an object (clause 10). If not, the behavior is undefined.

In the second alternative (delete array), the value of the operand of delete shall be the pointer value which resulted from a previous array new-expression. If not, the behavior is undefined.

So no : they are in no way equivalent !

http://en.wikipedia.org/wiki/Delete_(C%2B%2B)

In the C++ programming language, the delete operator calls the destructor of the given argument, and returns memory allocated by new back to the heap.[1] A call to delete must be made for every call to new to avoid a memory leak. After calling delete the memory object pointed to is invalid and should no longer be used. Many programmers assign 0 (null pointer) to pointers after using delete to help minimize programming errors. Note, however, that deleting a null pointer has no effect (if the deallocation function is one supplied in the standard library[2]), so it is not necessary to check for a null pointer before calling delete.

Example code snippet:

int *p_var = NULL;  // new pointer declared
p_var = new int;    // memory dynamically allocated
 
/* .......
other code
........*/
 
delete p_var;       // memory freed up
p_var = NULL;       // pointer changed to 0 (null pointer)

Arrays allocated with new [] can be similarly deallocated with delete []:

int size = 10;
int *p_var = NULL;       // new pointer declared
p_var = new int [size];  // memory dynamically allocated
 
/* .......
other code
........*/
 
delete [] p_var;         // memory freed up
p_var = NULL;            // pointer changed to 0

Arrays, allocated with new[], must be deallocated with delete[], since the layout of arrays allocated with new[] is implementation defined,[citation needed] and possibly not compatible with new. For example, in order to properly perform object destruction at delete[], some implementations of new[] embed the number of allocated objects into the beginning of the allocated memory chunk, and return pointer to the remaining part of the array.[citation needed]

The delete operator (user defined) is different from operator delete. The delete operator may call operator delete to free up memory.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值