tags:

views:

1221

answers:

5

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 by in essense is a non-const 'method'. Why is this allowed ? Is just to support this:

delete this;

Or is there some other reason?

+21  A: 

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.

anon
+1 for latest your edit. I think this is true reason. Automatic destructor call for const object - the almost same as delete f; where f - pointer on const.
bb
+8  A: 

Put it this way - if it weren't allowed there would be no way to delete const objects without using const_cast.

Semantically, const is an indication that an object should be immutable. That does not imply, however, that the object should not be deleted.

Visage
+2  A: 

Constructors and Destructors should not be viewed as 'methods'. They are special constructs to initialise and tear down an object of a class.

'const pointer' is to indicate that the state of the object would not be changed when operations are performed on it while it is alive.

Indeera
+1  A: 

FWIW const declarations are just a help for the programmer - that is why it is allowed to change a const ptr to a normal and back as C++ keeps the flexibility from C to be able to shoot yourself in the foot, although more elegantly.

Anders K.
+2  A: 

Another way to look at it: the precise meaning of a const pointer is that you will not be able to make changes to the pointed-to object that would be visible via that or any other pointer or reference to the same object. But when an object destructs, all other pointers to the address previously occupied by the now-deleted object are no longer pointers to that object. They store the same address, but that address is no longer the address of any object (in fact it may soon be reused as the address of a different object).

This distinction would be more obvious if pointers in C++ behaved like weak references, i.e. as soon as the object is destroyed, all extant pointers to it would immediately be set to 0. (That's the kind of thing considered to be too costly at runtime to impose on all C++ programs, and in fact it is impossible to make it entirely reliable.)

Daniel Earwicker