c++ returning into method of deleted object

377 Views Asked by At

This is a variation on the delete this debate, to do with what happens with intermediate method calls.

Basically, if method A calls method B, and method B destroys the object, does anything particular happen inside method A when returning from B? Something like this:

struct test {
  void A() {
    B();
    // what happens here besides being unable to dereference `this` anymore?
  }
  void B() {delete this;}
};

Can it be assumed that returning into a method of an expired object will proceed as normal as long as the memory location of the former object isn't interacted with any further?

2

There are 2 best solutions below

2
Bathsheba On BEST ANSWER

It's fine subject to:

  1. The object must have been created with new. (Note that a delete following a placement new would not be fine).

  2. Don't call any member functions or access member data after calling delete this; (functions re-entered due to stack unwinding are fine).

  3. Don't attempt to assign a pointer type to this.

So, in your case, there is no issue (assuming you're compliant with 1).

2
Hatted Rooster On

Nothing bad would happen. Of course there are obvious things to pay attention to like:

  • Be sure that the object this points to was allocated with new.
  • Do not call any other member functions after B() and do not access any member variables after B().
  • Do not use this for anything after B(), no, not even the pointer itself.