Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator overload which permits capturing with rvalue but not assigning to

Is it possible to design and how should I make overloaded operator+ for my class C to have this possible:

C&& c = c1 + c2;

but this not possible:

c1 + c2 = something;

Edit: I changed objects to small letters. c1, c2 and c are objects of class C. && is not the logical operator&&, but rather an rvalue reference.

For example writing:

double&& d = 1.0 + 2.0;

is 100% proper (new) C++ code, while

1.0 + 2.0 = 4.0;

is obviously a compiler error. I want exactly the same, but instead for double, for my class C.

Second edit: If my operator returns C or C&, I can have assignment to rvalue reference, but also assignment to c1 + c2, which is senseless. Giving const here disables it, however it disables assignment to rvalue too. At least on VC++ 2k10. So how double does this?

like image 225
Argbart Avatar asked May 04 '11 22:05

Argbart


1 Answers

Have the assignment operator be callable on lvalues only:

class C
{
    // ...

public:

    C& operator=(const C&) & = default;
};

Note the single ampersand after the closing parenthesis. It prevents assigning to rvalues.

like image 185
fredoverflow Avatar answered Nov 16 '22 00:11

fredoverflow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!