From: Martin B. on
Johannes Schaub (litb) wrote:
> Francis Glassborow 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. ....
>>>
>> ..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)
>>
>
> That sounds like a bad advice to me. As others pointed out, returning by
> reference to const is not bad and does not open any "worm-holes". I would
> and i do that by default. And only if it matters, i would return by value
> (see the ScopeGuard idiom).
>

I think the advice to generally return-by-value is *good*. Returning
by-const-ref does *only* make sense if you are directly returning a
member of the object. On the other hand, returning by-value Just Works,
regardless of what you are returning.

I agree that ... string const& get_ref() { return m_str; } ... is pretty
harmless, especially if you assign the result to a string object as
opposed to a reference. (As I have pointed out in another reply though,
*if* you assign to an object, then often there isn't *any* performance
gain of ret-by-ref - see RVO)

cheers,
Martin

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