Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use const& to this?

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==.

like image 560
dvicino Avatar asked Mar 15 '15 02:03

dvicino


1 Answers

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
};
like image 174
Ben Voigt Avatar answered Sep 29 '22 12:09

Ben Voigt