c++ - 运算符删除标准行为

标签 c++

我无法理解为 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/

相关文章:

c++ - 图像处理项目照片中光照水平变化的样本

c++ - 模式识别和字符串匹配

c++ - 二叉表达式树 C++

C++:带有默认参数的派生类中的运算符 <<?

c++ - 未定义对 'some_function' 的引用?

c++ - 将 IPv6 地址转换为 Internet 标准点分十进制格式的 ASCII 字符串

c++ - Windows 10 上的 GetTickCount 值

c++ - 在方法中更改现有数组,C++ 样式?

android - 如何使用 Assimp 库渲染 3D 文件

c++ - friend 模板参数相关查找