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; }
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.
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.
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.
“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.
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 are violating the #3 by accessing pi
after delete this
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With