Possible Duplicates:
C++: Delete this?
Object-Oriented Suicide or delete this;
I'm learning C++ by reading the very good book C++ Primer and I'm learning how C++ deallocates memory by the delete
keyword like C does with free
. Java and Pascal do not have this mechanism for explcitly freeing memory. It could lead to errors in programs if they run for long time and variables are destroyed that are needed so it should not be trivialized.
In short I wonder if it's legal or advicable for instance in C++ for a variable to do this.delete()
and delete itself. We mostly hear about freeing pointers in C and C++ and this is done with new free
and delete
keywords. Pascal also has pointers but Java has not. So in Java it should not be possible since you do not explicitly delete objects, C doesn't have objects so a struct
couldn't free
the memory it was allocated even if it was technically possible since C does not have objects and neither does Pascal.
So I suppose that leaves C++ for my question whether it is legal for an object to delete itself with something like this.delete()
?
It's perfectly possible for an object to do delete this;
.
However, after doing so, using this
is an undefined behaviour.
So, if you are very careful with was is done afterward, it's fine and legal for an object to "commit suicide" by doing delete this;
But, It's really not a good idea, especially because it means that your class should only be instanciated by new, as an allocation on te stack could cause the destructor to be called twice: by the delete this, and when going out of context.
The following example shows why it's not a good idea:
class A
{
public:
~A() { std::cout << "Destructor"; }
void foo() { delete this; }
};
int main()
{
{
A a;
a.foo(); // OK, a is deleted
} // Going out of context, the destructor is called again => undefined behavior
return 0;
}