From: Nevin :-] Liber on
In article
<f2c7aae7-1a13-4f5e-a634-09ba3da27f9b(a)f16g2000yqm.googlegroups.com>,
Zachary Turner <divisortheory(a)gmail.com> wrote:
> Maybe I'm still not understanding something, but by returning const
> reference you get a strict superset of the functionality possible when
> returning by value, with no downsides.

The downside is aliasing, which can both interfere with an optimiser and
requires programmers that use it to be much more careful. It makes it
harder to reason about the code.

The bugs caused by aliasing tend to be subtle and hard to find.

For instance, think about the algorithm behind vector::push_back(T
const& x). The obvious (psuedocode) implementation of

if (notEnoughSpace)
{
AllocateBiggerBuffer();
CopyOrMoveElements();
DestroyOldBuffer();
}
AddElementToTheBack(x);

is incorrect because of possible aliasing; think about the case of

v.push_back(v[0]);

> So I don't see why you would
> not want to do it.

If at all possible, I'd rather avoid constructs that lead to subtle bugs
and harder to reason about code. Premature, unmeasured optimisation is
not a good reason to adopt this construct.

I'll only use it if the semantics require that I refer to the same
object or it is a *measured* performance bottleneck in my application.
Return by value is my default behavior.

--
Nevin ":-)" Liber <mailto:nevin(a)eviloverlord.com> 773 961-1620

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]