简体   繁体   中英

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

As TC 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 }; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM