方法可以将&&作为参数说明的一部分,从而指定右值引用参数。看例子:
[cpp] view plaincopyprint
#include
using namespace std;
void showMax(int &a,int &b){
if(a>b)
cout<
else
cout<
}
int main()
{
int a=10;
int b=5;
showMax(a,b);
//showMax(20,15); // invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'|
cin.get();
return 0;
}
发现showMax(20,15)的时候无法正常编译。
这是因为20,15是一个右值。下面我们定义一个右值引用版本的showMax();
[cpp] view plaincopyprint
#include
using namespace std;
void showMax(int &a,int &b){
if(a>b)
cout<
else
cout<
};
void showMax(int &&a,int &&b){
cout<<"这是一个右值引用比较"<
if(a>b)
cout<
else
cout<
}
int main()
{
int a=10;
int b=5;
showMax(a,b);
showMax(20,15);
return 0;
}
运行结果:

当调用showMax(20,15)的时候,编译器将自动调用相对应的右值引用的版本。
作为方法的参数的时候右值引用非常有用,又例如:
[cpp] view plaincopyprint
#include
using namespace std;
void show(int &a){
cout<<"左值引用:"<
};
void show(int &&a){
cout<<"这是一个右值引用:"<
}
int main()
{