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()
?
delete this;
is perfectly valid syntax in C++ and should compile and execute "correctly". However, it assumes that*this
is allocated in the heap which ain't necessarily so. Further, it risks further memory corruption because once freed the space formerly occupied by*this
can be re-used by later memory allocations. Bad idea. Run away! Run away! – Cuesta