Re: pros and cons of returning const ref to string instead of string by value
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.
This is slightly misleading IMHO. Consider:
struct X
{
std::string m_s;
const std::string& s() const
{
return m_s;
}
};
.....
X x;
const std::string& r = x.s(); // affected by subsequent x destruction
std::string s = x.s(); // not affected by subsequent x destruction
It's not the return type of the function which affects this per se. I'm
not sure this is a reason to prefer return by value.
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.
Yes - if you return by value, you can return a string you constructed on
the fly. This can be an important consideration when you're designing an
interface - other people's subclasses may not want to have to store a
string to return here.
FWIW, I'm not sure the performance either way is going to make a huge
difference with just a string. That being said, I generally do return by
const reference with things like this unless I can see a good reason to
do otherwise. Purely on the basis that I might be able to avoid a copy
here or there - it almost certainly won't affect performance in a
significant way, but aside from the interface issue I mentioned, there
aren't all that many downsides I've encountered. YMMV.
Regards,
Stu
Regards,
Andrew Marlow
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]