Possible Duplicate:
Is it OK to use “delete this” to delete the current object?
I just saw some code where they have done delete this;
in a class function, I know that this is not a good design but is it defined what will happen, lets say that the class always is a pointer from somewhere. Will it always be deleted in the correct way?
class A
{
public:
void abort() { delete this; }
};
class B
{
void func() { A* a = new A; a->abort(); }
};
It is perfectly legal in C++ to delete this
and is actually very useful for certain patterns like smart pointers. The burden is on the developer though to make sure that no other methods are called or on the stack for this
which will access instance data after the delete occurs.
The C++ FAQ Lite has an entry for this which is worth reading
It is not the case that delete this;
is bad design, and it definitely does not result in undefined behaviour. It does what you would expect -- it deletes this object. That means you had better make really sure that you don't do anything else with the object after delete this
has been called.
The Microsoft MFC classes use delete this;
extensively, for instance in the CWnd (window) class. When a window receives the WM_DESTROY message, the window wrapper class (which is what the C++ object is) is no longer needed, so it calls delete this;
(I think in PostNcDestroy()
, somewhere like that). It's very neat from the point of view of the user of the framework: you just need to remember that there are ways for the C++ object to get deleted automatically and be a little careful near the end of the window's lifetime.
I am sure there are many other real-world examples where delete this;
is a useful paradigm.
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