[英]Is it undefined behaviour to delete a null void* pointer?
我知道delete
null 指针是一个空操作:
在任一替代方案中,如果 delete 操作数的值是 null 指针,则该操作无效。
(C++ 标准5.3.5 [expr.delete] p2
)
此外,删除void*
指针是未定义的行为,因为无法调用析构函数,因为没有void
类型的对象:
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 representing a base class of such an object. 如果不是,则行为未定义。
(C++ 标准5.3.5 [expr.delete] p2
)
现在,通常我认为首先列出的内容会覆盖稍后列出的内容,但是 null void*
指针如下所示呢?
void* p = 0;
delete p; // UB or well-defined?
我想知道只有当它是 null 时,你才能达到删除指针的情况。 但停留在语言律师模式...
5.3.5/1
delete 的操作数应具有指针类型或 class 类型,具有单一转换为指针类型。
void* 是指针类型,因此 null void 指针满足 static 要求。
5.3.5/2
在任一备选方案 [
delete
和delete[]
] 中,如果 delete 的操作数的值是 null 指针,则操作无效。
这给出了想要的行为。
5.3.5/3
In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behavior is undefined .
这无关紧要,null 指针不引用要检查附加约束的 object。
5.3.5/1
The operand shall have a pointer to object type, or a class type having a single non-explicit conversion function (12.3.2) to a pointer to object type.
void* 不是指向 object 类型的指针,因此应该被拒绝。
§5.3.5/3 说,
In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behavior is undefined . 在第二种选择(删除数组)中,如果要删除的 object 的动态类型与其 static 类型不同,则行为未定义73
在脚注中说,
73 -这意味着不能使用 void* 类型的指针删除 object,因为没有 void 类型的对象。
所以,是的,它的UB。
现在一旦进入行为不定之城,它的null与否都无所谓,因为它的行为不能精确地保持明确,因为它已经在行为不明的城市中获得了住所。
编辑:
得到了另一个主题,它也引用了相同的内容并说它的 UB:
我相信它未定义的行为。 不允许使用new void
(不允许创建void
类型的对象),因此在void*
上调用delete
也不应该有意义。 它是否指向NULL
并不重要。 我永远不会在我的代码中的任何地方使用这样的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.