I know what a const
qualifier means in a method declaration (making *this
const), but I can't fathom what the ampersands in these lines means:
MyClass &operator =(const MyClass&) & = default;
// ^- this one
bool operator ==(const MyClass &right) const &;
// that one -^
Isn't decltype(*this)
always MyClass&
/ const MyClass&
? So what does the ampersand mean in here?
- So what does the ampersand mean in here?
It means 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.
You can define both (lvalue/rvalue ref-qualifier), and the appropriate one will be picked up by overload resolution. Such as:
bool operator ==(const MyClass &right) const &;
bool operator ==(const MyClass &right) const &&;
- Isn't decltype(*this) always MyClass& / const MyClass&?
Note the type of *this
won't change even in the rvalue ref-qualified function.
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.