Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning const values to leverage move semantics vs preventing stuff like (a+b)=c [duplicate]

I think this question was slightly misunderstood.

Returning const values is not something that can be dismissed as meaningless. As Adam Burry pointed out in a comment, Scott Meyers recommends it in More Effective C++ (Item 6), to which I would add Herb Sutter's Exceptional C++ (Item 20, Class Mechanics, whose corresponding GotW is available online).

The rationale for doing this is that you want the compiler to catch typos like (a+b)=c (oops, meant ==), or misleading statements like a++++, both of which are flagged out-of-the-box for primitive types like int. So for stuff like operator+ and operator++(int), returning a const value does make sense.

On the other hand, as has been pointed out, returning a const prevents C++11's move semantics from kicking in, because they require a non-const rvalue reference.

So my question is, can we really not have our cake and eat it? (I couldn't find a way.)

like image 701
Julian Avatar asked Jul 28 '14 08:07

Julian


1 Answers

What you may do instead of returning const element is to restrict the method to lvalue object:

struct S
{
    S& operator =(const S& rhs) & // note the final &
                                  // to restrict this to be lvalue
    {
        // implementation
        return *this;
    }
};

So with

S operator +(const S& lhs, const S& rhs);
S a, b, c;

The following is illegal:

(a + b) = c;

Live example

like image 176
Jarod42 Avatar answered Oct 23 '22 06:10

Jarod42