2

An object a of class A calls an object b of class B, through a pointer:

void A::fun(){
  bPtr->delete_me();
}

In the called function we delete the calling object through a pointer (which was stored earlier):

void B::delete_me(){
  delete aPtr;
}

Is this safe, given that A does not access any of its members after calling bPtr->delete_me();?

Martin G
  • 17,357
  • 9
  • 82
  • 98
  • delete_me() would inspire `delete this`. Which is safe when no other references exist. `delete aPtr` is a wholeheckofalot riskier since the destructor still needs to run. Which ought to be expected to do something with aPtr. Like deleting it, that won't end well. Set to nullptr to avoid the heck. – Hans Passant Sep 18 '19 at 09:58

1 Answers1

7

Is this safe, given that A does not access any of its members after calling bPtr->delete_me();?

Yes. It's very similar to delete this;, which has been discussed here.

lubgr
  • 37,368
  • 3
  • 66
  • 117
  • You are also assuming that there are no dangling references or pointers to the destroyed `A` which are subsequently used to access its members. – Peter Sep 18 '19 at 09:48
  • 4
    @Peter You always assume that when you `delete` something. – Max Langhof Sep 18 '19 at 09:49
  • @MaxLanghof - Sure. And how many bugs are caused because some code assumes something is true, when it really is not? My point is that more assumptions are being made in the question than just "`A` does not access any of its members ...". And, for `pPtr->delete_me()` to successfully destroy the `A`, it must be accessing the address of the `A` from somewhere else. – Peter Sep 18 '19 at 09:54