Prev: pros and cons of returning const ref to string instead of string by value
Next: pros and cons of returning const ref to string instead of string by value
From: Andy Venikov on 2 Dec 2009 15:14 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 > Frankly, what you describe seems like a perfect fit for using shared_ptr Have your member be a shared_ptr<std::string>. And return shared_ptr<const std::string> from your getter function. Andy. -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |