Re: Can I return a reference to a string I just created?
On Apr 23, 12:44 pm, ugnonim...@gmail.com wrote:
string& myFunc()
{
string myString("some data");
....
return myString;
}
When does the string I created get deleted? Is it the same as this:
string& myFunc2()
{
return string("some other data");
}
Returning a reference is not a good idea, since, in this case, you are
returning a reference to a local object. The lifetime of a local
object ends with the termination of the method. If you do not return
by value, then a copy is made on the stack. If you wish to return by
reference, then you need to ensure that the object will not go out of
scope:
string& myFunc( string& someString )
{
string* resultString;
resultString = &someString;
someString = "My, how I've changed.";
return *resultString;
}
int main( )
{
string aString( "Hi, I am a string." );
cout << myFunc( aString ).c_str() << endl; // prints "My, how I've
changed."
cout << aString.c_str() << endl; // prints "My, how
I've changed."
return 0;
}
Robert Marion
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]