Question

Consider a class defined as below:

struct A
{
    void f();
    void f() const;
    void f() &;
    void f() const &;
    void f() &&;
    void f() const &&;
};

What are the differences between:

1) void A::f(); and void A::f() &; (Please notice this!)

2) void A::f() const; and void A::f() const &;

3) void A::f() &&; and void A::f() const &&;

Was it helpful?

Solution

You can transform these to

void f(A&);
void f(const A&);

void f(A&);
void f(const A&);
void f(A&&) &&;
void f(const A&&);

The first is special - it is a A&, but still accepts rvalues, unlike other non-const lvalue references. In all other regards, it is the same as any other function with a A& parameter.

There is no difference in overload resolution between the second (const) and the fourth (const&), except if they respectively compete against a (&&). I don't think that can happen for normal functions, but only for conversion functions, because the Standard forbids this case (in general, if there is any function in the current scope with a ref qualifier, all functions must)

void f();
void f() &&;

But with conversion functions, you can still have an overload resolution set with both operator int() and operator long()&&. In that case, even if the object on which they are invoked is R() (an rvalue), if you need to convert to int then the first conversion function would be used.

OTHER TIPS

  1. f() is a normal function for f() const, this must point to a modifiable lval
  2. f() const is a const function (cannot change this) f() const &is the same but guarantees this is an lval as well
  3. f()&& this must be a temporary value for f() const && this must be a temporary value that you cannot modify
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top