7

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.)

Community
  • 1
  • 1
Julian
  • 4,170
  • 4
  • 20
  • 27
  • I think the "advantage" of returning `const` has been over-stated before. Changing the semantics of a function just to avoid some possible typo seems like overkill. So I would say, you don't even want to eat the cake, it isn't a very tasty one. – juanchopanza Jul 28 '14 at 08:29
  • 1
    You can use reference qualifiers to constrain your `operator =` etc. – T.C. Jul 28 '14 at 08:30
  • 1
    Are move semantics really relevant for the return value of `operator=`? I can't think of any case in well written code where they would be. (One can construct artificial examples, but they wouldn't occur in well written code.) – James Kanze Jul 28 '14 at 08:34

1 Answers1

10

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

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Nitpick of the week: It's only *illegal* in a jurisdiction whose laws incorporate the C++11 standard. I know of none such, so you should probably say the code is *ill-formed*. Also, you should probably answer the duplicate instead of this question - it could use a recent answer. – Casey Jul 28 '14 at 16:11