标准库move函数
我们可以通过调用std::move函数来获得绑定到左值上的右值引用,此函数定义在头文件<utility>中。std :: move用于指示对象obj可以“移动”,即允许资源从obj到另一个对象的有效传输。注意,对move我们不应该使用using声明,而是应该直接调用std::move而不是move,以避免名字冲突。
int && rr3 = std::move(rr1);
move告诉编译器:我们有一个左值,但我们希望像一个右值一样处理它。我们必须认识到,调用move就意味着:除了对 rr1 赋值或销毁外,我们再使用它。在调用move之后,我们不能对moved-from对象(即rr1)做任何假设。
#include <iostream>
#include <utility>
#include <vector>
#include <string>
int main()
{
std::string str = "Hello";
std::vector<std::string> v;
// uses the push_back(const T&) overload, which means
// we'll incur the cost of copying str
v.push_back(str);
std::cout << "After copy, str is \"" << str << "\"\n";
// uses the rvalue reference push_back(T&&) overload,
// which means no strings will be copied; instead, the contents
// of str will be moved into the vector. This is less
// expensive, but also means str might now be empty.
v.push_back(std::move(str));
std::cout << "After move, str is \"" << str << "\"\n";
std::cout << "The contents of the vector are \"" << v[0]
<< "\", \"" << v[1] << "\"\n";
}