Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting objects using a member function in C++

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,

like image 359
Didac Perez Parera Avatar asked Nov 24 '25 19:11

Didac Perez Parera


2 Answers

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.

like image 150
Lightness Races in Orbit Avatar answered Nov 26 '25 12:11

Lightness Races in Orbit


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.

like image 20
Nikos Athanasiou Avatar answered Nov 26 '25 11:11

Nikos Athanasiou