“delete this” in C++

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.

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

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

using namespace std;
class A
  int x;
    A() { x = 0;}
    void fun() {
      delete this;
      /* Invalid: Undefined Behavior */

The best thing is to not do delete this at all.

Thanks to Shekhu for providing above details.


This article is contributed by Rahul Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up

Improved By : DeepakTiwari2

Practice Tags :
Article Tags :

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:

2.3 Average Difficulty : 2.3/5.0
Based on 41 vote(s)

User Actions