I have an Item class that defines its own new operator and the delete operator as follows:
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; };
I create an object of this type using the new placement, and then delete it as follows:
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; }
Output:
My Operator New. ID/extra: 1/haha Ctor: AC Milan before delete Destructor: AC Milan My Operator Delete after delete
As you can see, delete pI calls my own delete function, which does nothing but log output. However, from the output, the Item destructor is called in delete pI , which is not called in my own delete function.
So, in this case, the destructor will be called implicitly in the overloaded delete function?
c ++ destructor delete-operator
Tim_King
source share