左值和右值,最直观的理解就是:等号=左边的是左值,右边的是右值。
准确的说一下,左值与右值的定义:
左值引用是具名变量值的别名,而右值引用则是不具名(匿名)变量的别名。
那哪些属于右值呢?
右值引用由&&定义:
#include <iostream>
using namespace std;
int func(){
int a = 10;
return a;
}
void func1(int&& a){
cout << a << endl;
}
int main(){
int && b = func();
cout << b << endl;
return 0;
}
有一个很有意思的事情:能够接受右值的右值引用本身却是一个左值。
int && b = func();
cout << &b << endl; //可以取地址
不可以将左值作为参数传给需要右值的地方:
#include <iostream>
using namespace std;
int func(){
int a = 10;
return a;
}
void func1(int&& a){
cout << a << endl;
}
int main(){
int a1 = 100;
func1(a1);
return 0;
}
上面这么写会报错的:
rvalue.cpp:17:8: error: cannot bind rvalue reference of type ‘int&&’ to lvalue of type ‘int’
17 | func1(a1);
可以改为下面这样:
#include <iostream>
using namespace std;
int func(){
int a = 10;
return a;
}
void func1(int&& a){
cout << a << endl;
}
int main(){
int && b = func();
//cout << &b << endl; //可以取地址
int a1 = 100;
func1(move(a1));
return 0;
}
因为std::move会产生右值。
对了,右值引用有啥用呢?
(欲知后事如何,窃听下文分解,还没时间写呢。)