右值引用
左值变量是可以作为左值的的量。数字是没办法作为左值。
右值变量一般是常量才可以作为右值。
右值引用是对常量的引用
比如i=1,int &a=i,a是左值引用,因为i是个左值。
int &&a=45 a就是右值引用。因为45是个右值。
我们可以实现如下函数
#include #include using namespace std; class Test { public: Test() { } Test(const Test &t) { cout << “copy constructer” << endl; } Test &operator=(const Test&t) { cout << “assgign constructer” << endl; return *this; } Test(Test &&t) { cout << “&& copy constructer” << endl; } Test &operator=(Test&&t) { cout << “&& assgign constructer” << endl; return *this; } }; void display(int &&a) { cout << "Rgith " << a << endl; } void display(int &a) { cout << "Left " << a << endl; } int main() { int a = 0; display(a); display(10);
Test ab; ab = Test();//Test()operator=(Test&&t); vector vec; vec.push_back(Test());//Tset也是个临时变量,会调用Test(Test &&t)
Test abc(std::move(ab));//会调用Test(Test &&t) system(“pause”); return 0; } 整体执行效果: 避免复制数据,可以提高程序的效率 右值引用就是对临时变量的引用
