针对低效的处理临时变量(纯右值)的情况,C++11增加了一种称为将亡值的右值,从名字上可以看出,这是指将要消亡的值。引入将亡值的概念,主要目的是基于右值引用可以对讲这些将要消亡的值进行转移,有点借尸还魂的意思。
#include <iostream>
using namespace std;
class A{
public:
A()
{
cout<<"Construct A, this addr:"<<this<<endl;
}
A(const A &a)
{
cout<<"Copy Construct A, ori addr:"<<&a<<" this addr:"<<this<<endl;
}
~A()
{
cout<<"Destruct A, this addr:"<<this<<endl;
}
};
A getA()
{
return A();
}
int main(){
A&& a3 = getA(); //通过右值引用,让a3直接引用了getA返回的临时对象上
cout<<"a3 addr:"<<&a3<<endl;
return 0;
}
运行程序输出:
//return A()构造的临时对象,记作对象a1
Construct A, this add