1

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?

Xeren Narcy
  • 875
  • 5
  • 15

2 Answers2

2

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

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 3
    You answered faster than I could find a suitable duplicate. That's not praise, btw. – Cheers and hth. - Alf Sep 13 '17 at 12:20
  • this came up for me not so much because of `delete this` but because of a garbage collector running parallel to a queue of objects. the way that queue is processed involves recursive method calls at times, so it's possible to detect when an object is deleted in my case, not worried about interacting with dead objects. however had doubts about stack unwinding behavior, turns out it's fine if you're careful, thanks! – Xeren Narcy Sep 13 '17 at 12:30
2

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.
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122