1

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?

Kijewski
  • 25,517
  • 12
  • 101
  • 143
  • 2
    This means the method can only be called on an lvalue of `MyClass` type (as opposed to an rvalue). So that one can't do `MyClass() = my_class_instance` or `functionReturningMyClass() = my_class_instance`. Similarly, `&&` after closing paren means "only callable on rvalue". – Igor Tandetnik Aug 03 '16 at 14:16
  • To the down voter: Ever tried to google for special characters? Doesn't work very well. @IgorTandetnik, why didn't you put your comment as an answer? – Kijewski Aug 03 '16 at 14:19
  • 1
    @Kay likely because he knew it would be dupe-hammered and wanted to avoid posting a duplicate answer on a duplicate question. – jaggedSpire Aug 03 '16 at 14:26

1 Answers1

3
  1. 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 &&;
  1. 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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405