HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

Is "delete this" allowed in C++?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
alloweddeletethis

Problem

Is it allowed to delete this; if the delete-statement is the last statement that will be executed on that instance of the class? Of course I'm sure that the object represented by the this-pointer is newly-created.

I'm thinking about something like this:

void SomeModule::doStuff()
{
    // in the controller, "this" object of SomeModule is the "current module"
    // now, if I want to switch over to a new Module, eg:

    controller->setWorkingModule(new OtherModule());

    // since the new "OtherModule" object will take the lead, 
    // I want to get rid of this "SomeModule" object:

    delete this;
}


Can I do this?

Solution

The C++ FAQ Lite has an entry specifically for this

  • https://isocpp.org/wiki/faq/freestore-mgmt#delete-this



I think this quote sums it up nicely

As long as you're careful, it's OK for an object to commit suicide (delete this).

Context

Stack Overflow Q#3150942, score: 293

Revisions (0)

No revisions yet.