Suppose I have a class Foo
with a std::string
member str
. What should get_str
return?
std::string Foo::get_str() const
{
return str;
}
or
const std::string& Foo::get_str() const
{
return str;
}
What is more idiomatic in C++?
The short answer is: it depends :-)
From the performance point of view returning a reference is (usually) better: you save the creation of a new std::string
object. (In this case, the creation is costly enough and the size of the object is high enough to justify make this choice at least worth considering - but this is not always the case. With a smaller or built-in type the performance difference may be negligible, or returning by value may even be cheaper).
From the security point of view returning a copy of the original value may be better, as constness can be cast away by malicious clients. This is especially to be taken into consideration if the method is part of a public API, i.e. you(r team) have no full control over how the returned value is (mis)used.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With