这就是我正在做的事情:
#include <iostream>
using namespace std;
class Test
{
public:
int i;
Test();
Test(int x);
~Test();
static void operator delete(void * t);
};
Test::Test() : i(1) { cout << "constructing" << endl; }
Test::Test(int x) : i(x) { cout << "constructing w/ arg" << endl; }
Test::~Test() { cout << "destructing" << endl; }
Test::operator delete(void *self)
{
cout << "deleting" << endl;
((Test *) t)->~Test(); // call destructor since it isnt called otherwise
::delete(t); // actually delete memory
}
template <typename T> // too lazy to figure out correct type
void callback(Test *t, T fn)
{
(fn)(t); // delete operator is implicitly static so this syntax is correct
}
int main()
{
Test *t = new Test();
callback(t, &Test::operator delete); // deletes t
}
我注意到除非operator delete
为我的类重载,否则前面的代码段将无法编译。如果包含它,它将按预期编译和工作(首先调用构造函数,然后重载删除,然后是析构函数,每个都恰好一次)。
我想过传递全局删除运算符::operator delete
,但这也不起作用(我得到一个未解决的重载函数调用)。我可以调用它而无需尝试获取它的地址。
如果没有定义我自己的重载,我正在做的事情是否可能::operator delete
?
我知道基本上没有用例需要我使用这样的东西。我知道这::operator delete
不是通用的东西,而且它不调用析构函数....