阅读 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 namedoperator 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/