我在子类中重载了 operator new/delete,我注意到一种对我来说似乎很奇怪的行为。看看下面的示例代码:
#include <stdlib.h>
#include <stdio.h>
class Base
{
public:
virtual ~Base()
{
}
};
class Derived : public Base
{
public:
void* operator new(unsigned int size, int capacity)
{
printf("> new(unsigned int, int)\n");
return malloc(sizeof(Derived));
}
void operator delete(void* ptr, int)
{
printf("> delete(void*, int)\n");
free(ptr);
}
void operator delete(void* ptr)
{
printf("> delete(void*)\n");
free(ptr);
}
};
int main(int argc, char** argv)
{
Base* base = new (0) Derived();
delete base;
return 0;
}
此代码在使用 Visual Studio 2010 编译时生成以下输出:
> new(unsigned int, int)
> delete(void*)
为什么Derived::operator delete(void*, int)
这里没有调用匹配的删除运算符 ( )?无论我做什么,我都无法获取调用匹配运算符删除的代码。