best way to return an std::string that local to a function

Viewed 106166

In C++ what is the best way to return a function local std::string variable from the function?

std::string MyFunc()
{
    std::string mystring("test");
    return mystring;

}

std::string ret = MyFunc(); // ret has no value because mystring has already gone out of scope...???
7 Answers

None of the previous answers contained the key notion here. That notion is move semantics. The std::string class has the move constructor, which means it has move semantics. Move semantics imply that the object is not copied to a different location on function return, thus, providing faster function execution time.

Try to step debug into a function that returns std::string and examine the innards of that object that is about to be return. You shall see a member field pointer address xxx. And then, examine the std::string variable that received the function's return value. You shall see the same pointer address xxx in that object.

This means, no copying has occurred, ladies and gentlemen. This is the move semantics, God bless America!

Related