c++c++11callstackself-destruction

c++ returning into method of deleted object


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?


Solution

  • 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).