Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is move semantics just a shallow copy and setting other's pointers to null?

I've been reading about move semantics in C++, and in the explanations people give a lot of analogies to help simplify it, and in my head all I can see is that what people call "moving" as opposed to "copying" is just a shallow copy of the object and setting any pointers in the "moved-from" object to null. Is this basically the gist? Shallow copy and set other's pointers to null?

like image 259
Zebrafish Avatar asked Jan 02 '17 09:01

Zebrafish


1 Answers

Shallow copy and set other's pointers to null?

Shallow copy - yes. Setting other's pointers to null - not always.

The minimum requirement is that the moved-from object is in an "undefined but valid state", which is to say that you can reassign to it, move it again or delete it without causing the program to fail, but perform no other state-dependent operation on it. This means that it's perfectly valid in general to implement move-assignment in terms of std::swap.

Some objects define a stronger contract. One of these is std::unique_ptr. Moving-from one of these will result in it containing null, but this is explicitly documented.

like image 125
Richard Hodges Avatar answered Oct 07 '22 01:10

Richard Hodges