C++11为成员函数提供了通过左值调用还是右值调用的装饰词:
cpp
#include <iostream>
using namespace std;
class A{
public:
void fun() &{
cout << "fun() &" << endl;
}
void fun() &&{
cout << "fun() &&" << endl;
}
};
A createA(){
return A();
}
int main(){
A a;
a.fun(); // 调用 fun() &
createA().fun(); // 调用 fun() &&
return 0;
}
运行程序输出:
fun() &
fun() &&
可见通过这种方式,我们可以区分通过左值还是右值来调用成员函数。