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.