My question is simple: if I have some class Man and I want to define member function that returns man\'s name, which of the following two variants shall I prefer?
Fi
use the first variant:
string name();
The compiler will most likely optimize out any unnecessary copies. See return value optimization.
In C++11, move semantics means that you don't perform a full copy even if the compiler doesn't perform RVO. See move semantics.
Also bear in mind that if the alternative is
void name(std::string& s);
then you have to specify very clearly what can happen to s
and what values it can have when passed to the function, and probably either do a lot of validity checking, or simply overwrite the input entirely.