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.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With