在 c + + 0x 中删除 nullptr 是否仍然安全?

c++03中,删除空指针显然没有效果。事实上,§5.3.5/2明确指出:

在这两种情况下,如果 delete 操作数的值是 null 指针,则操作没有效果。

然而,在目前的 草稿 for c++0x中,这个句子似乎缺失了。在草案的其余部分,我只能找到一些句子来说明如果 Delete-expression 删除表达式的操作数不是空指针常量会发生什么。删除空指针是否仍然在 c++0x中定义,如果是,在哪里?

备注:

有相当多的间接证据表明,它仍有明确的定义。

首先,在 §5.3.5/2中有两个句子说明

在第一种选择(delete 对象)中,delete 操作数的值可以是空指针值,..。

还有

在第二种选择(delete 数组)中,delete 操作数的值可以是空指针值或..。

它们表示允许操作数为 null,但是它们本身并不实际定义如果为 null 会发生什么。

其次,改变 delete 0的含义是一个重大的突破性变化,标准委员会不太可能做出这种特殊的改变。此外,在 c++0x草案的兼容性附件(附件 C)中没有提到这是一个突破性的变化。然而,附录 C 是一个信息部分,所以这与标准的解释没有关系。

另一方面,要求删除空指针不产生任何效果的事实意味着额外的运行时检查。在许多代码中,操作数永远不能为空,因此这个运行时检查与零开销原则相冲突。也许委员会只是决定改变行为,使标准 c + + 更加符合语言的设计目标。

80515 次浏览

5.3.5/7 says:

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.

And 3.7.4.2/3 says:

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.

So the behavior is well defined, as long as the standard deallocation function is used, or a user-provided deallocation function handles null pointers correctly.

On the other hand, the fact that deleting the null pointer is required to have no effect implies an additional run-time check.

The new wording does not remove that run-time check for a null pointer. The other way around: draft standard comes even closer to saying that an implementation must make a null pointer test to be compliant.

Also noteworthy: The old standard contradicted itself in that it said (5.3.5/2) that "if the value of the operand of delete is the null pointer the operation has no effect" but later said that (5.3.5/7) the "delete-expression will call a deallocation function." Calling a function is an effect. This is particularly so since the function that is called might well be an overridden operator delete.

The new wording removes that contradiction, explicitly leaving it up to the implementation whether the deallocation function is called in the case of deleting a null pointer.