Return an object declared on stack

S

stub

My understanding is that "MyString" is created within the function of "emit"
on stack. How could the value of "MyString" be returned to the caller
successfully?

string emit()
{
string MyString("This is a string from emit()");
return MyString;
}

int main()
{
string YourString;
YourString = emit();
...
}
 
A

Ali R.

What you have is correct.

At the return of the emit function, a copy of MyString is sent back, and in
main the assignment operator is used to assign the value in the return value
to YourString.

Ali
 
B

Bob Hairgrove

My understanding is that "MyString" is created within the function of "emit"
on stack. How could the value of "MyString" be returned to the caller
successfully?

string emit()
{
string MyString("This is a string from emit()");
return MyString;
}

int main()
{
string YourString;
YourString = emit();
...
}

There will be a temporary string object created from MyString which is
then returned. It is only bad to return a reference or pointer to an
object which is created on the stack because it goes out of scope when
the function returns. The temporary will last until its value is used
by the object to which it is assigned.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,145
Messages
2,570,826
Members
47,373
Latest member
Desiree036

Latest Threads

Top