delete NULL会怎样?

根据C++标准草案,在尝试删除空指针时,实际上什么也不会发生。但删除操作并不会将指针值设为NULL,因此建议在删除后手动将指针置空。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文在此:[url=http://blog.aggregatedintelligence.com/2009/04/can-you-delete-null-pointer.html]Can you delete a NULL pointer?[/url]
没全转过来,只是留个记录。

根据目前的C++草案,[url=http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2008/n2798.pdf]Working Draft, Standard for Programming Language C++[/url]
[quote="Working Draft, Standard for Programming Language C++"]5.3.5 (6): If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted. In the case of an array, the elements will be destroyed in order of decreasing address (that is, in reverse order of the completion of their constructor; see 12.6.2).[/quote]
它说如果不是空指针就调用析构函数。换句话说delete NULL;什么也不会发生。

不过delete一个指针并不会改变指针的值(不会在delete后将指针设为NULL),所以调用了delete之后最好自己把指针设为空指针,
delete ptr;
ptr = NULL;


===================================

Hmm,想起之前读到的一些可怕的代码。像这种:
if (flag == false) {
// ...
}

这样写太容易出错了。习惯直接用!不好么……
if (!flag) {
// ...
}

而if (flag == true)就更糟糕了……直接if (flag)就完事了嘛。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值