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

C++Return Value

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

There will be a problem if your code is like:

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

So, the way you've written it is OK. Just one advice - if you can construct the string like this, I mean - you can do it in one row, it's sometimes better to do it like this:

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

Or if it's more "complicated", for example:

std::string MyFunct( const std::string& s1,
                     const std::string& s2,
                     const char* szOtherString )
{
    return std::string( "test1" ) + s1 + std::string( szOtherString ) + s2;
}

This will give a hint to your compiler to do more optimization, so it could do one less copy of your string (RVO).

Solution 3 - C++

As mentioned, the std::string is copied. So even the original local variable has gone out of scope, the caller gets a copy of the std::string.

I think reading on RVO can totally clear your confusion. In this case, it's accurately referred to as NRVO (Named RVO) but the spirit is the same.

Bonus reading: The problem with using RVO is that it's not the most flexible thing in the world. One of the big buzzes of C++0x is rvalue references which intends to solve that problem.

Solution 4 - C++

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!

Solution 5 - C++

Have you tried it? The string is copied when it's returned. Well that's the official line, actually the copy is probably optimised away, but either way it's safe to use.

Solution 6 - C++

Well, ret will have a value of mystring after MyFunc(). In case of returning the result by value a temporary object is constructed by copying the local one.

As for me, there are some interesting details about the topic in these sections of http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.9">C++ FAQ Lite.

Solution 7 - C++

It depends on the use case. If an instance should keep responsibility for a string, strings should be returned by a const reference. The problem is, what to do, if there isn't any object to return. With pointers, the invalid object could be signaled using 0. Such a "null-object" could be also used with references (e.g., NullString in the code snippet).

Of course, a better way to signal an invalid return value is throwing exceptions.

Another use case is if the responsibility for the string is transferred to the caller. In this case auto_ptr should be used. The code below shows all this use cases.

#include <string>
#include <memory> //auto_ptr
#include <iostream>

using std::string;
using std::auto_ptr;
using std::cout;
using std::endl;

static const string NullString("NullString\0");


///// Use-Case: GETTER //////////////////
//assume, string should be found in a list
//  and returned by const reference

//Variant 1: Pseudo null object
const string & getString( bool exists ) {
  //string found in list
  if( exists ) {
    static const string str("String from list");
    return str;
  }
  //string is NOT found in list
  return NullString;
}

//Variant 2: exception
const string & getStringEx( bool available ) {
  //string found in list
  if( available ) {
    static const string str("String from list");
    return str;
  }

  throw 0; //no valid value to return
}

///// Use-Case: CREATER /////////////////
auto_ptr<string> createString( bool ok )
{
  if( ok ){
    return auto_ptr<string>(new string("A piece of big text"));
  }else{
    return auto_ptr<string>();
  }
}

int main(){
  bool ok=true, fail=false;
  string str;
  str = getString( ok );
  cout << str << ", IsNull:"<<( str == NullString )<<endl;
  str = getString( fail );
  cout << str << ", IsNull:"<<( str == NullString )<<endl;

  try{
    str = getStringEx( ok );
    cout << str <<endl;
    str = getStringEx( fail );
    cout << str <<endl; //line won't be reached because of ex.
  }
  catch (...)
  {
    cout << "EX: no valid value to return available\n";
  }

  auto_ptr<string> ptext = createString( ok );
  if ( ptext.get() ){
    cout << *ptext << endl;
  } else {
      cout << " Error, no text available" << endl;
  }

  ptext = createString( fail );
  if ( ptext.get() ){
    cout << *ptext << endl;
  } else {
      cout << " Error, no text available"<<endl;
  }

  return 0;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTony The LionView Question on Stackoverflow
Solution 1 - C++ChubsdadView Answer on Stackoverflow
Solution 2 - C++Kiril KirovView Answer on Stackoverflow
Solution 3 - C++kizzx2View Answer on Stackoverflow
Solution 4 - C++eigenfieldView Answer on Stackoverflow
Solution 5 - C++Martin BroadhurstView Answer on Stackoverflow
Solution 6 - C++Paul E.View Answer on Stackoverflow
Solution 7 - C++Valentin HView Answer on Stackoverflow