Search code examples
c++stdstring

std::string as out parameter or return value


Which is the correct way to get an std::string value from a function. The assumption here is that I am writing the function and the caller.

std::string foo()
{
     std::string str = "ABC";
     return str;
}

OR

void foo(std::string &str)
{
    str = "ABC";
}

I understand that in the first method compiler optimizations will come into the picture and return by value will not be a big overhead so this method should be just fine.

The second method guarantees that there is no copy involved so it's going to be always efficient.

Which method would be your choice?


Solution

  • As said in the comments, using a return by value seems to be preferred nowadays. I find my code to be more readable that way, in that you can see that there is actually a change.

    With the out parameter foo(str) it's not obvious that str is being changed.

    I believe all mainstream compilers are clever enough to optimize away any unnecessary copying.

    So, in essence, it's more about readability and clarity than anything else.