C++ 中成员函数的 const& 、 & 和 && 说明符
const& , & and && specifiers for member functions in C++
最近我正在通读 API of boost::optional
并且遇到了以下几行:
T const& operator *() const& ;
T& operator *() & ;
T&& operator *() && ;
我还编写了自己的程序,将成员函数定义为 const&、& 和 &&(请注意,我不是在谈论 return 类型,而是在分号之前的说明符)并且它们似乎工作正常。
我知道将成员函数声明为const是什么意思,但是谁能解释一下将其声明为const&、&和&&是什么意思。
const&
意味着,此重载将仅用于常量、非常量和左值对象。
const A a = A();
*a;
&
表示,此重载将仅用于非常量对象。
A a;
*a;
&&
表示此重载将仅用于右值对象。
*A();
有关 C++11 标准的此功能的更多信息,您可以阅读此 post What is "rvalue reference for *this"?
是成员函数ref-qualifiers;它是 C++11 中添加的功能之一。通过指定函数引用限定符 (some details).
,可以根据隐式 this
对象参数是左值还是右值来重载非静态成员函数
要为非静态成员函数指定引用限定符,您可以使用 &
或 &&
.
限定函数
#include <iostream>
struct myStruct {
void func() & { std::cout << "lvalue\n"; }
void func() &&{ std::cout << "rvalue\n"; }
};
int main(){
myStruct s;
s.func(); // prints "lvalue"
std::move(s).func(); // prints "rvalue"
myStruct().func(); // prints "rvalue"
}
最近我正在通读 API of boost::optional
并且遇到了以下几行:
T const& operator *() const& ;
T& operator *() & ;
T&& operator *() && ;
我还编写了自己的程序,将成员函数定义为 const&、& 和 &&(请注意,我不是在谈论 return 类型,而是在分号之前的说明符)并且它们似乎工作正常。
我知道将成员函数声明为const是什么意思,但是谁能解释一下将其声明为const&、&和&&是什么意思。
const&
意味着,此重载将仅用于常量、非常量和左值对象。
const A a = A();
*a;
&
表示,此重载将仅用于非常量对象。
A a;
*a;
&&
表示此重载将仅用于右值对象。
*A();
有关 C++11 标准的此功能的更多信息,您可以阅读此 post What is "rvalue reference for *this"?
是成员函数ref-qualifiers;它是 C++11 中添加的功能之一。通过指定函数引用限定符 (some details).
,可以根据隐式this
对象参数是左值还是右值来重载非静态成员函数
要为非静态成员函数指定引用限定符,您可以使用 &
或 &&
.
#include <iostream>
struct myStruct {
void func() & { std::cout << "lvalue\n"; }
void func() &&{ std::cout << "rvalue\n"; }
};
int main(){
myStruct s;
s.func(); // prints "lvalue"
std::move(s).func(); // prints "rvalue"
myStruct().func(); // prints "rvalue"
}