Whilst refactoring some code I came across some getter methods that returns a std::string. Something like this for example:
class foo { private: std::string name_; public: std::string name() { return name_; } };
Surely the getter would be better returning a const std::string&? The current method is returning a copy which isn’t as efficient. Would returning a const reference instead cause any problems?
The only way this can cause a problem is if the caller stores the reference, rather than copy the string, and tries to use it after the object is destroyed. Like this:
However, since your existing function returns a copy, then you would not break any of the existing code.
Edit: Modern C++ (i. e. C++11 and up) supports Return Value Optimization, so returning things by value is no longer frowned upon. One should still be mindful of returning extremely large objects by value, but in most cases it should be ok.