c++ - 为什么在空指针上调用 "operator delete"时会调用 "delete"?

标签 c++ pointers memory-management

阅读 this question 的答案时我注意到答案(例如 this)暗示即使在空指针上执行 delete 语句时也可以调用 operator delete

所以我写了一个小片段:

class Test {
public:
    void* operator new( size_t ) { /*doesn't matter*/ return 0; }
    void operator delete( void* ptr ) {
        ptr; //to suppress warning and have a line to put breakpoint on
    }
};

int main()
{
    Test* ptr = 0;
    delete ptr;
}

而且 - 令我惊讶的是 - Test::operator delete() 被调用时 ptr 持有一个空指针。

据我了解,operator new 分配内存,operator delete 将内存返回给分配器。如果我在空指针上调用 delete 语句,则意味着指针后面没有对象,也没有内存可返回分配器。

delete 语句包括调用析构函数。当我传递一个空指针时,肯定不会调用析构函数——C++ 会处理这个问题。那为什么在这种情况下会调用operator delete呢?

最佳答案

即将发布的 C++0x 标准(第 5.3.5 节 [expr.delete])中的语言如下:

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. [ Note: The deallocation function is called regardless of whether the destructor for the object or some element of the array throws an exception. — end note ]

所以这是未指定的行为,一些编译器可能会在删除 NULL 指针时调用 operator delete 而其他编译器可能不会。

编辑:标准使用的术语 deallocation function 似乎引起了一些困惑。它带有引用。 3.7.4.2 [basic.stc.dynamic.deallocation] 中的一些关键语言可能有助于澄清:

If a class T has a member deallocation function named operator delete with exactly one parameter, then that function is a usual (non-placement) deallocation function.

标准也很明确,用户定义的operator delete需要接受一个为空指针值的参数:

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.

但是由于未指定的行为 5.3.5,您不应该依赖在指针为空时调用您的 operator delete

关于c++ - 为什么在空指针上调用 "operator delete"时会调用 "delete"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3821852/

相关文章:

c++ - 为什么模板内部的类型检查更严格?

c - 如果使用用户定义函数和 main() 函数访问全局声明的数组元素,为什么会得到不同的值?

java - 如何组合列表中的其他项目来为列表元素中的项目创建子集?

c - 使用相同的指针询问下一个值

c++ - 要释放动态数组初始化时程序崩溃

java - 安卓内存问题

c++ - 使用字符数组作为映射中的键

c++ - 字符串仅包含有效字符?

c++ - cMath 和 sin 函数的问题

c - 在 C 中处理结构数组