Printing border nodes of Binary Tree
January 24, 2013
Hamming distance
January 30, 2013

using delete operator on this

Can we use delete operator on this inside a class member function in C++, something like below:

    class TestClass
    {
        public:
            void myFunc()
            {
                delete this;
            }
    };

Solution:

Before getting into the solution, lets agree that this is a terrible-terrible coding to attempt to delete the this pointer inside a class.

Now, lets see the solution:

Ideally delete operator can be used to delete (deallocate) memory pointed to by any pointer (and also call the destructor function, in case of user defined types)

But, delete can only be used for memory which is allocated using new operator.

So, the below is Fine:

    TestClass * ptr = new TestClass;
    ptr->myFun(); // will deallocate memory pointed to by ptr.
    ptr = NULL;   // because ptr was a dangling pointer

If delete operator is used to delete this pointer for object not allocated on heap, then the behavior is undefined. as shown below:

    TestClass obj;
    obj.myFun(); // UNDEFINED

Please also note that you should not attempt to use any member of the class after deleting this, else the behavior is undefined.

Leave a Reply

Your email address will not be published. Required fields are marked *