I found some code like this:
class foo{
int a;
public:
foo(int v) : a{v} {}
bool operator==(const foo& rhs) const&{
return (rhs.a == a);
}
};
It compiles and runs.
I was wondering what are the benefits (or drawbacks) of having the reference (&) to this in the operator==.
As T.C. has been pointing out in comments, this reason for this is NOT "to accept only lvalues". const
references bind to rvalues just fine.
The reason for it is that functions can be overloaded on value category of the implicit object parameter only if ALL overloads specify a value category. That is, when you add an overload with &&
that matches only rvalues, it won't compile unless you add &
to the existing overload.
In 13.1, here is the wording of the rule:
Member function declarations with the same name and the same parameter-type-list as well as member function template declarations with the same name, the same parameter-type-list, and the same template parameter lists cannot be overloaded if any of them, but not all, have a ref-qualifier.
and gives an example
class Y { void h() &; void h() const &; // OK void h() &&; // OK, all declarations have a ref-qualifier void i() &; void i() const; // ill-formed, prior declaration of i // has a ref-qualifier };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With