在 c++03
中,很明显删除空指针没有任何效果。事实上,在 §5.3.5/2
中明确指出:
In either alternative, if the value of the operand of delete is the null pointer the operation has no effect.
但是,在当前 draft对于 c++0x
这句话似乎不见了。在草稿的其余部分,我只能找到说明如果 delete-expression 的操作数不是空指针常量会发生什么的句子。是否删除 c++0x
中仍然定义的空指针,如果是,在哪里?
注意事项:
有重要的间接证据表明它仍然是明确定义的。
首先,§5.3.5/2
中有两句话说明
In the first alternative (delete object), the value of the operand of delete may be a null pointer value, ...
和
In the second alternative (delete array), the value of the operand of delete may be a null pointer value or ...
这些说允许操作数为空,但它们本身并没有真正定义如果它是会发生什么。
其次,更改 delete 0
的含义是一项重大的重大更改,标准委员会不太可能做出此特定更改。此外,没有提到这是 c++0x
草案的兼容性附件(附件 C)中的重大更改。然而,附录 C 是一个信息性部分,因此这与标准的解释无关。
另一方面,删除空指针必须无效,这意味着额外的运行时检查。在很多代码中,操作数永远不能为空,因此这种运行时检查与零开销原则相冲突。也许委员会只是决定改变行为以使标准 c++ 更符合语言的既定设计目标。
最佳答案
5.3.5/7 说:
If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will call a deallocation function (3.7.4.2). Otherwise, it is unspecified whether the deallocation function will be called.
3.7.4.2/3 说:
The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect.
所以行为是很好定义的,只要使用标准的释放函数,或者用户提供的释放函数正确处理空指针。
关于c++ - 在 c++0x 中删除 nullptr 是否仍然安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6731331/