Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete vs operator delete (and void pointer)

Does delete ptr differ from operator delete(ptr) only in this, that delete calls ptr destructor? Or in other words, does delete ptr first call a destructor of ptr and then operator delete(ptr) to free allocated memory? Then is delete ptr technically equivalent to the following:

T * ptr = new T;

//delete ptr equivalent:
ptr->~T();
::operator delete(static_cast<void *>(ptr));

?

like image 339
mip Avatar asked May 13 '12 17:05

mip


People also ask

Can you delete a void pointer?

It is also called general purpose pointer. It is not safe to delete a void pointer in C/C++ because delete needs to call the destructor of whatever object it's destroying, and it is impossible to do that if it doesn't know the type.

When to use delete [] and delete?

delete is used for one single pointer and delete[] is used for deleting an array through a pointer. This might help you to understand better.

What is the delete operator?

The delete operator removes a given property from an object. On successful deletion, it will return true , else false will be returned.

What is delete operator in C++?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.


1 Answers

delete ptr will do overload resolution for operator delete, so it may not call the global ::operator delete

But otherwise, yes. The delete operator calls the relevant destructor, if any, and then calls operator delete.

like image 88
bames53 Avatar answered Sep 19 '22 15:09

bames53