-
How does delete work?
Hello everyone,
Just interested to learn how C++ implements delete this statement internally. From logical point of view, I can not imagine how to implement a component which destroy itself.
What makes me confused is the component is relying on itself even in the process of destroy, how could it destroys itself from itself?
thanks in advance,
George
-
delete de-allocates the memory held by the data after it has called the destructors for the actual object. So it's all fine to do that - the object is still there until the destructor has been finished, and then disappears.
Of course, you need to know that "this" points to memory allocated by new - otherwise you'll crash and burn.
--
Mats
-
I believe it works something like this:
Code:
delete pObj;
// becomes this:
try
{
pObj->~Object(); // Call the destructor.
}
catch (...)
{
std::terminate(); // Instantly kill the program if an exception is thrown.
}
free( pObj ); // Deallocate memory.
-
Code:
#include <iostream>
struct A
{
~A() {throw 1;}
};
int main()
{
try {
A* p = new A;
delete p;
}
catch (int n) {
std::cout << n << '\n';
}
}
Well, this doesn't terminate. It is however wrong to throw exceptions from the destructor because two exceptions must not be propagating at the same time (the destruction could be called because of another exception in the first place).
Concerning delete this;. Given the restrictions, I'm not so sure where it would be useful and why I wouldn't rather delete the object from the calling code. But you never know...
-
I've used delete this for deleting objects from a Factory class in a separate DLL. Something like this:
Code:
class CSomething
{
public:
void Delete() {delete this;}
...
};
Calling code would then delete the pointer safely (across module boundaries) by calling the Delete() member function for their object pointer.
Code:
CSomething* obj = factory.CreateSomething();
...
obj->Delete();
obj = NULL;
-
delete this; is required in implementing reference counted objects.
Since it doesn't delete the code that is executing out from under the processor, but only the data that it was once working on (and isn't now) then everything is fine.