std::move函数可以以非常简单的方式将左值引用转换为右值引用。(左值、左值引用、右值、右值引用 参见:http://www.cnblogs.com/SZxiaochun/p/8017475.html)
通过std::move,可以避免不必要的拷贝操作。
std::move是为性能而生。
std::move是将对象的状态或者所有权从一个对象转移到另一个对象,只是转移,没有内存的搬迁或者内存拷贝。
如string类在赋值或者拷贝构造函数中会声明char数组来存放数据,然后把原string中的 char 数组被析构函数释放,如果a是一个临时变量,则上面的拷贝,析构就是多余的,完全可以把临时变量a中的数据直接 “转移” 到新的变量下面即可。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void TestSTLObject()
{
std::string str = "Hello";
std::vector<std::string> v;
// push_back
v.push_back(str);
std::cout<<"After copy, str is : " << str <<endl;
// move
v.push_back(std::move(str));
std::cout<<"After move , str is : "<< str <<endl;
std::cout<<"The contents of the vector are: \r\n"<< v[0] <<endl << v[1]<<endl;
// use it again
str = "henry";
std::cout<<"After reuse , str is : "<< str <<endl;
std::cout<<"The contents of the vector are: \r\n"<< v[0] <<endl << v[1]<<endl;
}
int main()
{
TestSTLObject();
return 0;
}
//============= the result is : ============
After copy, str is : Hello
After move , str is :
The contents of the vector are:
Hello
Hello
After reuse , str is : henry
The contents of the vector are:
Hello
Hello
参考地址:https://www.cnblogs.com/szxiaochun/p/8017349.html