Re: pros and cons of returning const ref to string instead of string by value
Andrew wrote:
On 2 Dec, 22:00, Zachary Turner <divisorthe...@gmail.com> wrote:
On Dec 2, 7:06 am, Andrew <marlow.and...@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.
I don't like that argument. If I need to hold a string I need to hold a
string and not some reference to some internals of some object.
Note also that:
class Foo {
string s_;
public:
string get_s() { return s; }
string const& access_s() { return s; }
};
....
string x = obj.get_s();
string y = obj.access_s();
// Because of RVO, these two calls will copy the string exactly one
time, so ret-by-val does not decrease performance
string const& rz = obj.access_s();
// Generally saves one heap allocation, so is faster.
// However validity of rz is tightly coupled to state and lifetime of
obj, so the likelihood of crashes increases.
br,
Martin
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]