is there a language syntax for move rather the std::move
No. The only language syntax related to moves is rvalue references, which is what gives code the permission to move data from one object to another rather than copying the data, since the target of an rvalue reference is not expected to care about the data anymore after a move has been performed.
and how std::move
works?
std::move()
merely type-casts an lvalue reference into an rvalue reference, nothing more. It is the responsibility of the code that is receiving the rvalue reference to actually move data around as needed. Use of std::move()
does not guarantee that a move will actually be performed. It is merely providing permission to perform a move on an object that is not normally an rvalue.
In your example, std::move(v2)
casts v2
to a vector<string>&&
rvalue reference, and assigns that to v3
. No actual move is being performed, since v3
is just a reference that is not being used for anything. A more meaningful example would be:
vector<string> v1 = { "one", "two", "three", "four", "five" };
vector<string> v2(std::move(v1));
vector<string> v3;
v3 = std::move(v2);
std::vector
has a move constructor and a move assignment operator. In this case, v2
will steal the array from v1
leaving v1
empty, and then v3 will steal the array from
v2leaving
v2empty. There is only 1 physical array being allocated in memory, pointers to it are simply being moved around from one
vector` to another.
In the rule of five I have to define move constructor, what is the best practices?
Move what you need, and leave the source object in a "stable but unspecified" state. Which is just a fancy way of saying: steal away the source object's data, and make sure the source object is not left in a state where it will crash or otherwise have unspecified behavior because of the steal. Which, in most typical cases just means setting stolen pointers/handles to nullptr
/0.