views:

269

answers:

6

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...???
+21  A: 

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.

Chubsdad
+1 for pointing out the obvious to the asker. It's better to get the basics right before going into the details.
rwong
+4  A: 

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.

Martin Broadhurst
Actually, in the case of a class like std::string with a non-trivial copy constructor, it can't be optimised away, but it will be in cases where the class does have a trivial copy constructor.
Martin Broadhurst
@Martin -- "in the case of a class...with a non-trivial constructor, it can't be optimised away" -- Oh, but it can, and usually is. Try this: std::string * sp; std::string func(){ std::string s("bla"); sp = return s;}int main(){ std::string s = func(); if(sp == else std::cout << "BOO";} -- On my compiler (VS) It prints YAY.
PigBen
@Martin, what PigBen wrote of course results in undefined behavior, but even under defined circumstances the compiler has the right elide the copy sometimes. Google for RVO and NRVO.
avakar
@PigBen, @avakar, thanks for the correction. Scary!
Martin Broadhurst
+1  A: 

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.

kizzx2
@kizzx2: There are two flavors of RVO: URVO (Unnamed RVO) relates to temporaries and NRVO (Named RVO) relates to local variables. URVO is usually simpler (for the compiler). NRVO is more difficult, because with named variables you could have various `return` statement, each returning a different variable. At this point the optimizer has to pick **1** variable as the one being optimized, and all the other paths will yield a copy.
Matthieu M.
+4  A: 

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 ex:

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

Kiril Kirov
-1, read your second snippet again.
avakar
argh xD Yep.. but -1 for such mistake ? (:
Kiril Kirov
Why the explicit cast, anyway? Doesn’t that cloud the issue? Just doing `return "foo";` works like a charm.
Konrad Rudolph
Yep, it's the same. OK, I'll edit it, it's more clear (:
Kiril Kirov
+1  A: 

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 C++ FAQ Lite.

Paul HIQ
+1  A: 

It depends on use case. If instance should keep responsibility for string, stings should be returned by const reference. The problem is, what to do, if there is no object to return. With pointers the invalid object could be signalized using 0. Such a "null-object" could be also used with references (e.g. NullString in code snippet). Of cause better way to signal 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;
}

Best regards, Valentin Heinitz

Valentin Heinitz