#include <new>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
struct foo {};
inline void* operator new(size_t size, foo*) throw (std::bad_alloc)
{
std::cout << "my new " << size << std::endl;
return malloc(size);
}
inline void operator delete(void* p, foo*) throw()
{
std::cout << "my delete" << std::endl;
free(p);
}
int main()
{
delete new((foo*)NULL) foo;
}
输出(通过ideone):
my new 1
我的想法是 C++ 会释放一个带有附加参数的新对象,并匹配删除相同的参数,但我显然是不正确的。
让上面的代码调用我的重载删除的正确方法是什么?