What type of std :: move?

This code works as expected (online here ). At the end, v empty, and w not empty, since it typed the contents of v .

  vector<int> v; v.push_back(1); cout << "v.size(): " << v.size() << endl; auto vp = move(v); vector<int> w(vp); cout << "w.size(): " << w.size() << endl; cout << "v.size(): " << v.size() << endl; 

But if I replaced auto vp=move(v) with

  vector<int> && vp = move (v); 

Then he does not move. Instead, it copies and both vectors are not empty at the end. As shown here .

Explanation: In particular, what is a type with automatic vp production? If it is not vector<int> && , then what else could it be? Why do the two examples give different results, even though they are so similar?

Extra . I also tried this and it was still copying instead of moving

  std :: remove_reference< vector<int> > :: type && vp = move(v); 
+4
source share
3 answers

Edit to explain OP : auto -developed type move(v) - vector<int> . See C ++ 11 "auto" Semantics .

In the first example, this is:

 move 'v' into 'vp' copy 'vp' into 'w' 

and the second example:

 set 'vp' as rvalue-reference of 'v' copy 'vp' (which is 'v') into 'w' 

What std:move does is simply cast the type to rvalue (see What is std :: move () and when should it be used? ). Therefore in

 vector<int>&& vp = move(v); 

it just sets rvalue-reference vp to v and does nothing. In addition, rvalue-reference is an lvalue (has a name), therefore

 vector<int> w(vp); 

will call the copy constructor to copy vp (which v ) to w .

It will call the move constructor if you make the vp value rvalue ( Example ):

 vector<int> w(move(vp)) 

You can read the following: C ++ Rvalue Explained References .

+12
source

In the first case:

 auto vp = move(v); 

is equivalent to:

 vector<int> vp = move(v); 

This calls the move constructor, since move(v) is of type vector<int>&& , so vp finishes stealing the contents of v .

In the second case:

 vector<int>&& vp = move(v); 

just makes vp reference r-value to v . This does not call the move constructor or copy constructor, and nothing will be stolen.

+2
source
 auto vp = move(v); 

Creates a new vector<int> and calls its move constructor:

 vector(const vector<T>&& other); 

What will steal the contents v .

Thus, the type 'vp' is simply vector<int> .. there were no links:

 vector<int> vp; 

It β€œmoves” the insides, not the actual vector itself.

So, &vp will be different from &v .. but the content will move.

+1
source

Source: https://habr.com/ru/post/1386974/


All Articles