右值:
右值引用标记为&&,其中对于右值和左值的理解
1.左值是指存储在内存中,有明确存储地址(可取地址)的数据
2.右值是指可以提供数据值的数据(不可取地址)
右值引用:
右值引用就是对一个右值进行引用的类型。能够通过右值引用使右值的生命周期延长。该右值的声明周期和这个声明的右值引用变量的生命周期一样,只要这个变量还存在,这个右值变量将一直存活下去。
#include <iostream>
using namespace std;
int&& value = 520;
class Test
{
public:
Test()
{
cout << "construct: my name is jerry" << endl;
}
Test(const Test& a)
{
cout << "copy construct: my name is tom" << endl;
}
};
Test getObj()
{
return Test();
}
int main()
{
int a1;
int &&a2 = a1; // error
Test& t = getObj(); // error
Test && t = getObj();
const Test& t = getObj();
return 0;
}
其中a1是一个左值不能够用来对右值引用类型的a2进行初始化
而在getObj()中返回了一个Test对象,这个返回值是一个临时对象,因为它没有被命名