Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
401 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...