Friday, May 18, 2007

Deleting a const pointer

Never thought that one can delete a const pointer in c++ without performing a const_cast on it in c++.

Tested this with the below code sample
========================
class A { public: int l; };
void test ( const A *aObj) { delete aObj; }
main() {
A *aObj = new A();
test(aObj);
}

=========================

To my surprise the code works on gcc-4.0.

So one cant be relaxed by just giving away a const pointer. Only way you can restrict the user from deleting is by giving out a reference or using smart pointers.

Even if they dont allow delete on a const pointer. The user can still invoke the desctructor explicitly by calling 'aObj->~A()' which is just another public function. So it seems like its a conscious decision made by c++ gurus.

==================
main() {
const A *aobj = new A();
// there should be a way for him to cleanup this..
// So makes sense to have delete supported.
delete aObj;
}
=================

snippets of some discussion forums :

"

However, this was always a little bit inconsistent,
since C++ has always permitted destroying an object via a pointer to
const by explicitly invoking the destructor, as in `p->~Foo()'. When
the committee decided to allow `const Foo *p = new const Foo', it
became pretty clear that they also had to allow `delete p'. So since
November 94, C++ has allowed deleting a pointer to a constant object. "

References:
http://www.thescripts.com/forum/thread439679.html
http://cpptips.hyperformix.com/cpptips/delconst.txt

No comments: