【C++11右值引用】
1、什么是左值?什么是右值?
左值是表达式结束后依然存在的对象;右值是表达式结束时就不再存在的对象。
2、在早期的C++中,普通 & 无法对右值取引用。只有 const & 可以对右值取引用。
const int& i = 10;
右值引用能够解决两个问题。
1)非必要的拷贝操作
2)模板函数,按照实际类型进行转发
3、第一大特点:通过右值引用的声明,右值又“重获新生”
#include <iostream> using namespace std; int g_constructCount=0; int g_copyConstructCount=0; int g_destructCount=0; struct A { A(){ cout<<"construct: "<<++g_constructCount<<endl; } A(const A& a) { cout<<"copy construct: "<<++g_copyConstructCount <<endl; } ~A() { cout<<"destruct: "<<++g_destructCount<<endl; } }; A GetA() { return A(); } int main() { A a = GetA(); return 0; }