方法声明中 & 符号的含义

Meaning of ampersand in method declaration

我知道 const 限定符在方法声明中的含义(使 *this 常量),但我无法理解这些行中的符号的含义:

MyClass &operator =(const MyClass&) & = default;
//                                  ^- this one
bool operator ==(const MyClass &right) const &;
//                                 that one -^

decltype(*this) 不是总是 MyClass& / const MyClass& 吗?那么这里的符号是什么意思?

  1. So what does the ampersand mean in here?

表示ref-qualified member functions:

A non-static member function can be declared with either an lvalue ref-qualifier (the token & after the function name) or rvalue ref-qualifier (the token && after the function name). During overload resolution, non-static cv-qualified member function of class X is treated as a function that takes an implicit parameter of type lvalue reference to cv-qualified X if it has no ref-qualifiers or if it has the lvalue ref-qualifier. Otherwise (if it has rvalue ref-qualifier), it is treated as a function taking an implicit parameter of type rvalue reference to cv-qualified X.

您可以同时定义两者(lvalue/rvalue ref-qualifier),重载决议将选择合适的一个。如:

bool operator ==(const MyClass &right) const &;
bool operator ==(const MyClass &right) const &&;
  1. Isn't decltype(*this) always MyClass& / const MyClass&?

注意 *this 的类型即使在右值引用限定函数中也不会改变。

Note: unlike cv-qualification, ref-qualification does not change the properties of the this pointer: within a rvalue ref-qualified function, *this remains an lvalue expression.