Prev: pros and cons of returning const ref to string instead of string by value
Next: Partial Specialization of Template Function
From: Martin B. on 3 Dec 2009 22:57
Zachary Turner wrote:
> On Dec 3, 2:36 am, Andrew <marlow.and...(a)googlemail.com> wrote:
>> On 2 Dec, 22:00, Zachary Turner <divisorthe...(a)gmail.com> wrote:
>>> On Dec 2, 7:06 am, Andrew <marlow.and...(a)googlemail.com> wrote:
>>> Maybe I'm overlooking something, but I see little reason to return by
>>> value. What matters is whether you assign it to a const reference or
>>> to a value.
>> The view I am running into is that a function should return a const
>> ref to a string so that it can be assigned to a const ref to a string.
>> The argument is that doing this avoids string copying. I should have
>> made that clearer.
> Right. If you return by value, it always makes a copy. If you return
> by const reference, it makes a copy when you want it to make a copy,
> and doesn't make a copy when you don't want it to make a copy.
It is not generally true that "If you return by value, it always makes a
copy." - the reason is RVO.
In the presence of RVO, Initializing a string object with
return-by-value is exactly the same as return-by-reference (Assigning is
not however), i.e.:
// e.g. with VC8 or later *without* optimizations
s1 = f.get_byval(); // Needs temporary!
s2 = f.get_byref(); // No need for temporary
string s3 = f.get_byval(); // Does NOT need temporary
string s4 = f.get_byval(); // Does NOT need temporary
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]