Open In App
Related Articles

“delete this” in C++

Improve Article
Improve
Save Article
Save
Like Article
Like

Ideally delete operator should not be used for this pointer. However, if used, then following points must be considered.
1) delete operator works only for objects allocated using operator new (See this post). If the object is created using new, then we can do delete this, otherwise behavior is undefined.
 

CPP




class A
{
  public:
    void fun()
    {
        delete this;
    }
};
 
int main()
{
  /* Following is Valid */
  A *ptr = new A;
  ptr->fun();
  ptr = NULL; // make ptr NULL to make sure that things are not accessed using ptr.
 
 
  /* And following is Invalid: Undefined Behavior */
  A a;
  a.fun();
 
  getchar();
  return 0;
}


2) Once delete this is done, any member of the deleted object should not be accessed after deletion.
 

CPP




#include<iostream>
using namespace std;
 
class A
{
  int x;
  public:
    A() { x = 0;}
    void fun() {
      delete this;
 
      /* Invalid: Undefined Behavior */
      cout<<x; // this is working
    }
};
 
int main()
{
  A* obj = new A;
  obj->fun();
  return 0;
}


Output

0

The best thing is to not do delete this at all.
Thanks to Shekhu for providing above details.
References: 
https://www.securecoding.cert.org/confluence/display/cplusplus/OOP05-CPP.+Avoid+deleting+this 
http://en.wikipedia.org/wiki/This_%28computer_science%29
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 11 Nov, 2021
Like Article
Save Article
Previous
Next
Similar Reads