The Wayback Machine - https://web.archive.org/web/20240724064655/https://www.geeksforgeeks.org/delete-this-in-c/
Open In App

“delete this” in C++

Last Updated : 11 Nov, 2021
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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

 



Previous Article
Next Article

Similar Reads

C program to delete a file
The remove() function in C/C++ can be used to delete a file. The function returns 0 if the file is deleted successfully, Otherwise, it returns a non-zero value. The remove() is defined inside the &lt;stdio.h&gt; header file. Syntax of remove()remove("filename");ParametersThis function takes a string as a parameter, which represents the name of the
2 min read
C++ | new and delete | Question 2
Which of the following is true about new when compared with malloc. 1) new is an operator, malloc is a function 2) new calls constructor, malloc doesn't 3) new returns appropriate pointer, malloc returns void * and pointer needs to typecast to appropriate type. (A) 1 and 3 (B) 2 and 3 (C) 1 and 2 (D) All 1, 2 and 3 Answer: (D) Explanation: See mall
1 min read
C++ | new and delete | Question 3
Predict the output? #include &lt;iostream&gt; using namespace std; class Test { int x; Test() { x = 5;} }; int main() { Test *t = new Test; cout &lt;&lt; t-&gt;x; } (A) Compiler Error (B) 5 (C) Garbage Value (D) 0 Answer: (A) Explanation: There is compiler error: Test::Test() is private. new makes call to the constructor. In class Test, constructor
1 min read
C++ | new and delete | Question 4
What happens when delete is used for a NULL pointer? int *ptr = NULL; delete ptr; (A) Compiler Error (B) Run-time Crash (C) No Effect Answer: (C) Explanation: Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.Quiz of this Question
1 min read
C++ | new and delete | Question 5
Is it fine to call delete twice for a pointer? #include&lt;iostream&gt; using namespace std; int main() { int *ptr = new int; delete ptr; delete ptr; return 0; } (A) Yes (B) No Answer: (B) Explanation: It is undefined behavior to call delete twice on a pointer. Anything can happen, the program may crash or produce nothing. Quiz of this Question
1 min read
Queries to insert, delete one occurrence of a number and print the least and most frequent element
Given Q queries of type 1, 2, 3 and 4 as described below. Type-1: Insert a number to the list.Type-2: Delete only one occurrence of a number if exists.Type-3: Print the least frequent element, if multiple elements exist then print the greatest among them.Type-4: Print the most frequent element, if multiple elements exist then print the smallest amo
14 min read
Delete every Kth node from circular linked list
Delete every kth node from a circular linked list until only one node is left. Also, print the intermediate lists. Examples: Input : n=4, k=2, list = 1-&gt;2-&gt;3-&gt;4 Output : 1-&gt;2-&gt;3-&gt;4-&gt;1 1-&gt;2-&gt;4-&gt;1 2-&gt;4-&gt;2 2-&gt;2 Input : n=9, k=4, list = 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;9 Output : 1-&gt;2-&gt;3-&gt;4
13 min read
How to delete last element from a map in C++
If we wish to delete the last element from a map, we can use following methods : using prev(mp.end()) : what prev function do is, it goes back one step back from the given iterator. So using prev function with mp.end() will return an iterator which points the last element of the map. Implementation: #include &lt;bits/stdc++.h&gt; using namespace st
2 min read
How to delete an element from the Set by passing its value in C++
Given a Set, the task is to remove the last element from this Set in C++.Examples: Input: set = [10 20 30 70 80 90 100 40 50 60], valueOfElementToBeDeleted = 100 Output: 10 20 30 40 50 60 70 80 90 Input: set = [1 2 3 4 5], valueOfElementToBeDeleted = 3 Output: 1 2 4 5 Sets are a type of associative container in which each element has to be unique b
6 min read
How to delete a range of values from the List using Iterator
Given a List, the task is to delete a range of values from this List using Iterator. Example: Input: list = [10 20 30 40 50 60 70 80 90], start_iterator = 3, end_iterator = 8 Output: 10 20 80 90 Input: list = [1 2 3 4 5] start_iterator = 1, end_iterator = 3 Output: 3 4 5 Approach: In this method, a range of elements are deleted from the list. This
2 min read
Practice Tags :
three90RightbarBannerImg