9

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?

Community
  • 1
  • 1
aJ.
  • 34,624
  • 22
  • 86
  • 128

5 Answers5

13

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.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
4

As this answer says, delete is not a method like any other, but a part of the langage to destruct objects. const-ness has no bearing on destructability.

Community
  • 1
  • 1
David Schmitt
  • 58,259
  • 26
  • 121
  • 165
3

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.

How did you try this? It certainly does accept const pointers:

#include <memory>

int main() {
    void* const px = 0;
    delete px;
    ::operator delete(px);
}

This code is correct, compiles (albeit with a justified warning) and executes.

EDIT: Reading the original article – you aren't talking about a const pointer but a pointer to const, which is something else. The reason why this has to work is described there. As for why it's working: others have said this.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
1

delete is an operator that you can overload. It takes a pointer as an argument, and frees the memory, possibly using free. The compiler allows this whether the pointer is const or not.

Zifre
  • 26,504
  • 11
  • 85
  • 105
  • 5
    This isn't actually correct. A fine but important distinction has to be drawn between the operator `delete` (cannot be changed) and the function `operator delete` (which can be). The former calls the latter but they are *not* identical. – Konrad Rudolph Apr 16 '09 at 13:49
  • @Konrad Rudolph, yes, that's true, but it doesn't make that much of a difference. – Zifre Apr 16 '09 at 13:54
-1

delete just makes a call to deallocate the memory the pointer points to, it doesn't change the value of the pointer nor the object. Therefore, delete has nothing to do with the const-ness of the pointer or object pointed to.

Nick Strupat
  • 4,928
  • 4
  • 44
  • 56