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\");
ret
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
#include //auto_ptr
#include
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 createString( bool ok )
{
if( ok ){
return auto_ptr(new string("A piece of big text"));
}else{
return auto_ptr();
}
}
int main(){
bool ok=true, fail=false;
string str;
str = getString( ok );
cout << str << ", IsNull:"<<( str == NullString )< ptext = createString( ok );
if ( ptext.get() ){
cout << *ptext << endl;
} else {
cout << " Error, no text available"<
Best regards, Valentin Heinitz