Operator overload which permits capturing with rva

2020-02-01 04:50发布

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?

1条回答
Explosion°爆炸
2楼-- · 2020-02-01 05:24

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.

查看更多
登录 后发表回答