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

Tony The Lion picture Tony The Lion · Oct 20, 2010 · Viewed 90.5k times · Source

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...???

Answer

Chubsdad picture Chubsdad · Oct 20, 2010

No. That is not true. Even if mystring has gone out of scope and is destroyed, ret has a copy of mystring as the function MyFunc returns by value.