When should I use const & for this?

I found a 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 advantages (or disadvantages) have a link (&) to this in the == operator.

+8
c ++ reference this const
source share
1 answer

As TC pointed out in the comments, so for this, DO NOT “accept only lvalues”. const links bind to rvalues ​​just fine.

The reason for this is that functions can be overloaded in the category of values ​​of an implicit parameter of an object only if ALL overloads defines a category of values. That is, when you add an overload with && that matches only rvalues, it will not compile unless you add & to an existing overload.

In 13.1, the rule is stated here:

Declarations of member functions with the same name and the same list of type parameters, as well as declarations of templates of member functions with the same name, the same list of parameter parameters and the same lists of template parameters cannot be overloaded, if any Either of them, but not all, has 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 }; 
+4
source share

All Articles