On 2 Dec, 21:56, Francis Glassborow
<francis.glassbo...@btinternet.com> wrote:
> Andrew wrote:
> > When I write a method that returns a string I always return the string
> > by value. This is as opposed to returning a const reference to the
> > string held as a private data member in the object. Doing it my way
> > means that when the object goes out of scope, my string is still
> > valid. Doing it the other way means you HAVE to keep the object around
> > for as long as you have a reference to the string.
>
> > Can anyone think of any other reasons to prefer returning a string by
> > value. I am encountering some opposition to this, mainly in the name
> > of performance. The performance has not been measured (of course) but
> > this is often the case with 'performance' arguments. Unfortunately,
> > "show me the figures" cuts no ice.
>
> > Regards,
>
> > Andrew Marlow
>
> ..Certainly where performance is an issue, repeated copying of strings
> can cause a measurable loss in performance. However where the library
> uses the small string optimisation (no use of the heap) the loss is
> pretty small. And where you have an implementation that uses move
> semantics I would certainly default to using return by value and only
> move to return by reference where measurement showed a performance gain
> that was critical to the program (and with move semantics think that
> would be pretty uncommon)
No, you can't move from one to the other, it has to be all or nothing.
It is VERY dangerous to mix the two. Consider this:
string get_value() const;
const string& get_something() const
{
return get_value();
}
This will compile but will fail at runtime. get_something is returning
a reference to a temporary. The compiler will warn but many developers
routinely ignore compiler warnings. I just got bitten by this bug in
the project I am working on.
-Andrew Marlow
--
[ See
http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]