I fail to understand the real nature std::move
- They say that:
std::move(object)
returns "an Rvalue reference to that object". Yes, I got this. - They also say that: use
push_back(std::move(object))
instead ofpush_back(object)
to avoid copying. I didn't get this, because it seems to contradict with the example below:
#include <utility>
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
template <class T> void print(T const & object){
for (auto var : object){std::cout << ' '<<var;}
std::cout << '\n';
}
int main () {
std::string foo = "foo-string";
std::string bar = "bar-string";
std::vector<std::string> myvector = { "super", "vip" , "pro" , "ok" }; // capcity=size=4;
// this block is just to increase the capacity of the vector
myvector.push_back( "rango" ); //NOW: capacity = 8 , size =5
std::cout << &myvector[0] <<'\n'; //check the address of the first element of the vector
// this block is the point of the problem
myvector.push_back(foo); // copies -> YES!
myvector.push_back(std::move(bar)); // moves !?!?
std::cout << "myvector contains:";
print(myvector);
std::cout << &myvector[0] << '\n'; // re-check the address of first element of the vector = still the same.
std::cout << "the moved-from object: " << std::quoted(bar);
return 0;
}
- The address of first element of vector before and after
push_back(std::move(object))
is the same, meaning the address of the last element bypush_back
must be stored at "a fixed distance" from the first element (in this case) - So if we don't copy the object to the fixed given position, then how can we store the value of that object to "that position"?