Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does delete deal with pointer constness?

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:

  1. invoke destructor
  2. then releases the memory (often with a call to 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?

like image 217
aJ. Avatar asked Apr 16 '09 13:04

aJ.


People also ask

What happens to a pointer when you delete it?

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).

Does delete delete a pointer Yes No?

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.

What happens if you delete a pointer twice?

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.

Can you delete const pointers?

It is illegal to delete a variable that is not a pointer. It is also illegal to delete a pointer to a constant.


1 Answers

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.

like image 93
sharptooth Avatar answered Oct 22 '22 18:10

sharptooth