我无法理解为 void* == nullptr 调用 operator delete 需要做什么标准。
像这样:
void foo(void* ptr) // ptr == nullptr here
{
delete ptr;
}
一方面,我们在标准中有如下声明:
ISO/IEC 14882:2011
5.3.5 删除[expr.delete]
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. The result has type void.78
78) This implies that an object cannot be deleted using a pointer of type void* because void is not an object type.
这使得删除 void* 的代码格式错误。另一方面,我们还有一个关于delete中nullptr的声明:
ISO/IEC 14882:2011
5.3.5 删除[expr.delete]
2 ... In the first alternative (delete object), the value of the operand of delete may be a null pointer value, a pointer to a non-array object created by a previous new-expression, or a pointer to a subobject (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 may be a null pointer value or a pointer value that resulted from a previous array new-expression.79 If not, the behavior is undefined.
在这种情况下需要做什么实现?
最佳答案
Null 和 void*
是两个不同的东西:
delete static_cast<int*>(nullptr); // deleting null pointer, of int*
您给定的代码可能格式错误,但它与指针的值(可能为空)无关,但它的类型(不能是 void*
)。
关于c++ - 运算符删除标准行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15016634/