I don't understand if a move assignment is able/free to change the address of a variable x and invalidate all the pointers and references storing &x. I figure that it's false because a default move assignment move each member and preserve the this pointer but is it guaranteed ?
EDIT : Example
int x(1), y(2);
int& ref(x);
x = std::move(y);
// ref still valid ?
Moving to or from an object does not invalidate references or pointers to the object. The address of both objects remains the same.
References are just alternate names to existing objects. That is, x
and ref
are entirely interchangable (although I'm not sure if decltype(x)
and decltype(ref)
are identical): when x
changes using the other name ref
will correspondingly see the same change. Likewise, the other way around. The same is true with pointers to objects.
Invalidating references and pointers happens when the referenced entity somehow goes away. For example, when you have a reference to an element in a std::vector<T>
and the capacity of the vector changes, the reference is invalidated because the underlying object moves away.
Of course, for your example of int
using std::move(y)
is rather pointless anyway: the built-in types do not really have any move constructors, i.e., it is equivalent to a copy. However, even when using a class type, object and a reference to it still refer to the same object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With