2

From this question

Shortest and best way to "reinitialize"/clean a class instance

The answer to "Shortest and best way to “reinitialize”/clean a class instance" is

myUsedInstance = myClass();

Now my question is: Is it guaranteed that the memory address is the same after re-initializing? That is, if I have a pointer myClass* that points to myUsedInstance, will that pointer correctly point to the newly initialized object or is there anything I have to be careful of?

Community
  • 1
  • 1
chrise
  • 4,039
  • 3
  • 39
  • 74
  • Slightly related warning: if you do use placement new (as suggested by one of the answers in the linked question), *then* you need to "clean" your pointers with `std::launder` (at least with C++17) – Daniel Jour Mar 01 '17 at 11:33
  • this is just an assignment, no more than invoke a member function. – apple apple Mar 01 '17 at 11:43

1 Answers1

6

The assignment does not change the old object's identity, all pointers and references to it remain valid.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
  • Might want to also note that such an assignment relies on the class having both a working assignment operator and a constructor that can be called with no arguments. It won't compile otherwise. – Peter Mar 01 '17 at 11:51
  • 1
    @Peter If it doesn't even compile, we certainly don't have a problem with pointer invalidation. I don't think that's what this question is about, your remark seems to fall into the scope of the linked Q/A instead. – Baum mit Augen Mar 01 '17 at 11:53