Tuesday 16 January, 2007

delete this;

"delete this;" legal?

Yes! of course its legal, with certain restrictions.

Once you call 'delete this;' no member variables should be accessed, since they would have been deleted already.


class CTest
{
    int iInt;
    char *iStr;

    public:
        void func()
        {
            ...

            delete this; // object destroyed here

            ...

            iInt = 6;// Illegal! don't do this
        }
};


Also this is not valid if the object is created on stack. Following should not be done.


CTest obj;
obj.func(); // Not valid since obj is on stack

 

CTest *ptr = new CTest();
ptr->func();


// Valid, only if no members are accessed after delete this;


 


One more interesting fact! What if we use 'delete this;' in destructor? ;)
Of course it will create the recursion calls to destructor!!!


 

Is there any practical use of this then?

Yes!

Consider the scenario where I would want to restrict the user to be able to create an object only on heap. User should not be able to create the object on stack.

We can achieve this by making destructor private. There by preventing the stack unwinding to happen, which will intern avoid creating variables on stack. Then the user will only be able to create object on heap.


class COnlyOnHeap
{
    private:
        ~COnlyOnHeap(); // destructor made private
};

COnlyOnHeap obj; // Not possible since d'tor is private.
COnlyOnHeap *ptr= new COnlyOnHeap(); // Possible


We achieved our goal!


Object can only be created on heap but not on stack.


But, Wait!

How will u cleanup this?


We cannot say "delete ptr", because d'tor is private.


How will we cleanup this then?


The only way is to expose one more cleanup public function which does "delete this;"!



COnlyOnHeap::Cleanup()
{
    delete this; // This calls the private d'tor within the class
}


Enjoy C++

 

2 comments:

Anand Patil said...

Change this line,

Consider the scenario where I would want to restrict the user to be able to create an object on stack. User should be able to create the object only on heap.

To

Consider the scenario where I would want to restrict the user to be able to create class objects only on heap( Not allowing him to create objects on stack).

Prashanth Narayanaswamy said...

Thanks Anand, Typo has been corrected !