June 2013

Quick Q: Should I return a const value? -- StackOverflow

Quick A: No.

Some authors wrote "Consider doing this" in C++98. The answer is now a definite "No" because it prevents move from returned values.

Isn't the const modifier here unnecessary?

The "Effective C++" Item 3 says "Use const whenever possible", and it gives an example like:

 

const Rational operator*(const Rational& lhs,
                            const Rational& rhs);

to prevent clients from being able to commit atrocities like this:

Rational a, b, c;
...
(a * b) = c;   // invoke operator= on the result of a*b!

But isn't the non-reference return value of functions allready a rvalue? So why bother doing this?