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