美文网首页
rvalue reference

rvalue reference

作者: 令一 | 来源:发表于2015-07-10 11:11 被阅读0次

int i = 10;

int &lri = i;                   //left reference

const int &clri = 10;     //const left reference

int &&rri = 10;             //right reference

一个右值可以用常量左值引用绑定;

一个右值也可以用右值引用绑定;

不能将一个右值引用不能直接绑定到一个左值上: 

int &&rri = i; //error 

=>  int &&rri = std::move(i);

Note: 使用move函数意味着此对象是一个右值,是临时的,不能对它的值做任何假设。

例如,在vs2013中,调用move函数后的str值为空:

string str = "value";

vector<string>vs;

vs.push_back(str);

cout << str << endl;

vs.push_back(std::move(str));

cout << str << endl;           //str is empty

此处的两个push_back会分别调用其左值引用版本和右值引用版本。左值引用版本会调用copy构造函数,右值引用版本会调用移动构造函数。

void push_back(const value_type& _Val);

void push_back(value_type&& _Val);

相关文章

网友评论

      本文标题:rvalue reference

      本文链接:https://www.haomeiwen.com/subject/spcuqttx.html