I was reading this question Deleting a const pointer and wanted to know more about delete
behavior. Now, as per my understanding:
delete expression
works in two steps:
free()
) by calling operator delete.operator delete
accepts a void*
. As part of a test program I overloaded operator delete
and found that operator delete
doesn't accept const
pointer.
Since operator delete does not accept const pointer and delete internally calls operator delete, how does Deleting a const pointer work ?
Does delete
uses const_cast internally?
The address of the pointer does not change after you perform delete on it. The space allocated to the pointer variable itself remains in place until your program releases it (which it might never do, e.g. when the pointer is in the static storage area).
The delete operator does absolutely nothing to the pointer itself. The delete operator sends the object pointed to by the pointer back the heap, after running any required destructors. When the delete operator is finished, you a left with a pointer that points to memory you don't own.
If delete is applied to one of the pointers, then the object's memory is returned to the free store. If we subsequently delete the second pointer, then the free store may be corrupted.
It is illegal to delete a variable that is not a pointer. It is also illegal to delete a pointer to a constant.
const_cast doesn't really do anything – it's a way to suppress compiler moaning about const-ness of the object. delete keyword is a compiler construct, the compiler knows what to do in this case and doesn't care about const-ness of the pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With