This code works as expected (online here).
At the end v is empty and w is not empty as it has pilfered 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 replace auto vp=move(v) with
vector<int> && vp = move (v);
Then it doesn’t move. Instead it copies and both vectors are non-empty at the end. As shown here.
Clarification: More specifically, what is the auto-derived type of vp? If it’s not vector<int> &&, then what else could it be? Why do the two examples give different results despite being so similar?
Extra: I also tried this, and it still copied instead of moving
std :: remove_reference< vector<int> > :: type && vp = move(v);
Edit for OP’s clarification: the
auto-derived type ofmove(v)isvector<int>. See C++11 "auto" semantics.The 1st example does this:
and the 2nd example does this:
What
std:movedoes is simply casting a type to an rvalue (See What is std::move(), and when should it be used?). Therefore, init’s just setting the rvalue-reference
vptovand do nothing else. Also, an rvalue-reference is an lvalue (it has a name), sowill call the copy constructor to copy
vp(which isv) intow.It will call the move constructor if you make
vpan rvalue (Example):You may want to read this: C++ Rvalue References Explained.