I have class Item
which defines its own operator new and operator delete 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 by using a placement new and then delete 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;
}
The output is:
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 in which nothing is done except outputting a log. However, from the output, the destructor of Item
is called in delete pI
which isn't invoked in my own delete function.
So in this case, destructor would be called implicitly in a overloaded delete function?
new
and yourdelete
operators. You don't call the constructor in your overloadednew
operator either, and it is still called. The constructors and destructors are always called when using thenew
anddelete
operators. – Circumferentialwarning C4291: 'void *Item::operator new(std::size_t,int,const std::string &)': no matching operator delete found; memory will not be freed if initialization throws an exception
. – Petepetechia::operator new
function only allocates memory. That you don't have to specify class or type is a clear hint. – Circumferential