1 #include <iostream> 2 #include <utility> 3 #include <vector> 4 #include <string> 5 int main() 6 { 7 std::string str = "Hello"; 8 std::vector<std::string> v; 9 10 // uses the push_back(const T&) overload, which means 11 // we'll incur the cost of copying str 12 v.push_back(str); 13 std::cout << "After copy, str is "" << str << "" "; 14 15 // uses the rvalue reference push_back(T&&) overload, 16 // which means no strings will copied; instead, the contents 17 // of str will be moved into the vector. This is less 18 // expensive, but also means str might now be empty. 19 v.push_back(std::move(str)); 20 std::cout << "After move, str is "" << str << "" "; 21 22 std::cout << "The contents of the vector are "" << v[0] 23 << "", "" << v[1] << "" "; 24 }
最好配合着c++标准库一起看。