Suppose I have a class Foo
with a std::string
member str
. What should get_str
return?
std::string Foo::ge
One of the goals of having an accessor method is to try, at least to some extent, to abstract your class implementation from its interface.
Returning by value is better because there are no lifetime issues with the referenced object. Should you decide not to have a std::string
member but, say, a std::stringstream
or to create a std::string
on the fly you don't have to change the interface.
Returning by const
reference isn't the opposite of taking a parameter by const reference, taking a value by const
reference doesn't tie your internal data representation to the external interface.