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?

Add a Comment

Comments are closed.

Comments (3)

0 0

Leszek Swirski said on May 31, 2013 05:28 PM:

Apparently the correct way to do this is by forbidding operator= to be used on rvalues, using the following method declaration:
Rational &operator=(const Rational& other) &
Can someone point me to an explanation of this syntax? I'm familiar with const member functions of course, but I've never before seen a & (a reference?) member function.
0 0

Bartosz Bielecki said on Jun 3, 2013 02:17 PM:

@Leszek Swirski
http://stackoverflow.com/questions/8610571/what-is-rvalue-reference-for-this

Most probably you remember the syntax
void foo() const
so that you can define whether you can call a method on constant or mutable object. With the introduction of rvalrefs
foo()
matched both: the "temporary" rvalrefs and lvalues. This causes some problems where you could specialize
foo()
to work on temporary objects doing ponentially dangerous mutations, but allowing it as the object will go away very soon.

With the introduction of the
void foo() [const][&|&&]
syntax you can create overloads that will match
T&
,
const T&
,
const T&&
(don't ask me if it does make sense),
T&&
or
T[&|&&]
.
0 0

Leszek Swirski said on Jun 3, 2013 02:47 PM:

Yup, that makes perfect sense, thanks Bartosz!