Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does move assignment break the references?

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 ?
like image 247
Cevik Avatar asked Dec 11 '22 19:12

Cevik


2 Answers

Moving to or from an object does not invalidate references or pointers to the object. The address of both objects remains the same.

like image 143
eerorika Avatar answered Dec 13 '22 08:12

eerorika


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.

like image 28
Dietmar Kühl Avatar answered Dec 13 '22 08:12

Dietmar Kühl