Jan 292013
 

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.

pinkdiamonds.nl

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)