Having this:
class Foo
{
public:
void destroy() { delete this; }
public:
// Stuff here...
};
int main(int argc, char *argv[])
{
Foo* foo = new Foo;
// Option 1
delete foo;
// Option 2:
foo->destroy();
return 0;
}
Is Option 1 and Option 2 the same operation? Is it a 'correct' way for destroying objects? Why/Why not?
Thank you so much,
Yes, the two are equivalent in this case.
But you should definitely prefer Option 1. delete this is very easy to get wrong, violates various design principles, and in this instance is completely pointless.
Such destruction schemes (a member function deleting the this pointer) are the common solution when implementing classes that allow instances only on the heap
class Foo
{
~Foo(); // private destructor - won't allow objects on the stack
public:
void destroy() { delete this; }
public:
// Stuff here...
};
In the above example, the destructor can't be called, so you can't say
delete FooInstance;
and your only option to avoid memory leaks is to have a destroy function:
FooInstance->destroy();
Apart from that I haven't found any real world cases where such a destruction function is/has to be used.
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