Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what will happen if you do "delete this;" in a member function?

Tags:

What will exactly happen if a member function try to do delete this;, like in the constructor of the following class?

class A { public:     A(int);     ~A();     int *pi; }  A::A(int i) {     delete this;     pi = new int(i); }  A::~A() {     delete pi; } 
like image 396
zhanwu Avatar asked Aug 12 '11 11:08

zhanwu


People also ask

Can you call delete this inside a member function?

Answer: Yes, we can delete “this” pointer inside a member function only if the function call is made by the class object that has been created dynamically i.e. using “new” keyword. As, delete can only be applied on the object that has been created by using “new” keyword only.

What does delete this do in CPP?

Using the delete operator on an object deallocates its memory. A program that dereferences a pointer after the object is deleted can have unpredictable results or crash.

Can I call delete this?

It's safe to delete "this" as long as it's essentially the last operation in the method. In fact several professional level APIs do so (see ATL's CComObject implementation for an example). The only danger is attempting to access any other member data after calling "delete this". This is certainly unsafe.

Can you delete this in C ++?

“delete this” in C++ 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.


2 Answers

This C++ FAQ entry answers this quite nicely, repeating here:

As long as you're careful, it's OK for an object to delete this.

Here's how I define "careful":

  • You must be absolutely 100% positively sure that this object was allocated via new (not by new[], nor by placement new, nor a local object on the stack, nor a global, nor a member of another object; but by plain ordinary new).
  • You must be absolutely 100% positively sure that your member function will be the last member function invoked on this object.
  • You must be absolutely 100% positively sure that the rest of your member function (after the delete this line) doesn't touch any piece of this object (including calling any other member functions or touching any data members).
  • You must be absolutely 100% positively sure that no one even touches the this pointer itself after the delete this line. In other words, you must not examine it, compare it with another pointer, compare it with NULL, print it, cast it, do anything with it.

You are violating the #3 by accessing pi after delete this

like image 155
Alok Save Avatar answered Sep 20 '22 05:09

Alok Save


Bad things. You can delete this; but it's generally speaking an extremely bad idea, and once it's done, you cannot touch any member variables or member functions.

like image 34
Puppy Avatar answered Sep 19 '22 05:09

Puppy