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/hahaCtor: AC Milanbefore deleteDestructor: AC MilanMy Operator Deleteafter 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).
以上是内存溢出为你收集整理的c – 在重载的运算符删除函数中是否隐式调用析构函数?全部内容,希望文章能够帮你解决c – 在重载的运算符删除函数中是否隐式调用析构函数?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)