rvalue reference

In C++, there are rvalues and lvalues. An lvalue is an expression whose address can be taken, a locator value–essentially, an lvalue provides a (semi)permanent piece of memory. You can make assignments to lvalues.
An expression is an rvalue if it results in a temporary object.

比如说:

1
2
3
4
5
6
7
8
int a = 1;
string b = 'lijinlong';
int& getRef()
{
return a;
}
getRef() = 3;

其中a、b、getRef()都是lvalue。

1
2
3
4
5
6
string getName()
{
return "lijinlong";
}
getName();
string str(string("hahaha"));

getName()、string(“hahaha”)是rvalue。

C++11引入了RValue Reference,可以这样定义:

1
typename&& ref;

引入RValue Reference的目的是为了避免对临时变量不必要的复制。一般用在构造函数或者是=重载函数的参数上。
标准库中提供了std::move(lvalue)函数来把一个lvalue转换成一个rvalue。详细用法以及需要注意的问题见参考。

参考:
Move semantics and rvalue references in C++11