class Item { public: Item(const std::string &s):msg(s) { std::cout<<"Ctor: "<<msg<<std::endl; } static void* operator new(size_t size,int ID,const std::string &extra) { std::cout<<"My Operator New. ID/extra: "<<ID<<"/"<<extra<<std::endl; return ::operator new(size); } static void operator delete(void* p) { std::cout<<"My Operator Delete"<<std::endl; return; } ~Item() { std::cout<<"Destructor: "<<msg<<std::endl; } void Print() { std::cout<<"Item::msg: "<<msg<<std::endl; } private: std::string msg; };
我使用placement new创建了这种类型的对象,然后删除如下:
int main() { Item *pI=new(1,"haha")Item("AC Milan"); std::cout<<"before delete"<<std::endl; delete pI; std::cout<<"after delete"<<std::endl; return 0; }
输出是:
My Operator New. ID/extra: 1/haha Ctor: AC Milan before delete Destructor: AC Milan My Operator Delete after delete
正如您所看到的,删除pI调用我自己的删除功能,除了输出日志之外没有任何操作.但是,从输出中,Item的析构函数在delete pI中调用,而pI在我自己的delete函数中没有被调用.
解决方法
So in this case,destructor would be called implicitly in a overloaded delete function?
是.对于delete expression,(1)首先调用析构函数,然后(2)调用apporiate operator delete;在此阶段将执行名称查找和重载解析.
If expression is not a null pointer,the delete expression invokes the destructor (if any) for the object that’s being destroyed,or for every element of the array being destroyed (proceeding from the last element to the first element of the array).
After that,unless the matching new-expression was combined with another new-expression (since C++14) the delete expression invokes the deallocation function,either
operator delete
(for the first version of the expression) oroperator delete[]
(for the second version of the expression).