Search code examples
c++constantsdelete-operator

Deleting a pointer to const (T const*)


I have a basic question regarding the const pointers. I am not allowed to call any non-const member functions using a const pointer. However, I am allowed to do this on a const pointer:

delete p;

This will call the destructor of the class which in essence is a non-const 'method'. Why is this allowed? Is it just to support this:

delete this;

Or is there some other reason?


Solution

  • It's to support:

    // dynamically create object that cannot be changed
    const Foo * f = new Foo;
    
    // use const member functions here
    
    // delete it
    delete f;
    

    But note that the problem is not limited to dynamically created objects:

    {
     const Foo f;
     // use it
    } // destructor called here
    

    If destructors could not be called on const objects we could not use const objects at all.