Best Way to Return String in C++

c++string

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?

First:

string name();

Second:

void name(/* OUT */ string &name);

The first variant is kind of inefficient because it makes unnecessary copies (local variable -> return value -> variable in the left part of assignment).

The second variant looks pretty efficient but it makes me cry to write

string name;
john.name(name);

instead of simple

string name(john.name());

So, what variant shall I prefer and what is the proper trade-off between efficiency and convenience/readability?

Best Answer

It's a good question and the fact that you're asking it shows that you're paying attention to your code. However, the good news is that in this particular case, there's an easy way out.

The first, clean method is the correct way of doing it. The compiler will eliminate unnecessary copies, in most cases (usually where it makes sense).

EDIT (6/25/2016)

Unfortunately it seems that David Abaraham's site has been offline for a few years now and that article has been lost to the ethers (no archive.org copy available). I have taken the liberty of uploading my local copy as a PDF for archival purposes, and it can be found here.

Related Question