user997112
user997112

Reputation: 30655

Stack variable being returned

I was reading the following question:

How to "return an object" in C++?

(which asks about returning objects in C++)

and in particular, the following answer:

https://stackoverflow.com/a/3350418/997112

Thing calculateThing() {
    Thing thing;
    // do calculations and modify thing
     return thing;
}

surely this answer won't work because the variable defined will no longer exist, as it was on the stack and only in scope for the duration of the function?

Upvotes: 0

Views: 94

Answers (3)

masoud
masoud

Reputation: 56549

The thing inside that function will destroy after return, but it will be copied to another Thing object at caller side.

Thing new_thing = calculateThing();

new_thing has the content of returned thing from calculateThing.

Note: There is a tricky point, I assume there is well defined copy-constructor or assignment-operator, in case of have new/delete stuffs in Thing.

UPDATE: As juanchopanza commented, RVO will avoid creating thing inside that function. In fact new_thing will replaced by thing implicitly and an extra copy will not be done. Obviously no destruction will be happen.

Upvotes: 1

Mankarse
Mankarse

Reputation: 40643

This works because thing is copied/moved in to the return value (the return value is a different object from thing unless copy elision takes place, in which case the lifetime of thing is extended to the lifetime of the return value).

//Here there may be up to three Thing objects.
//- `thing` in the function body
//- the unnamed temporary that is the value of `calculateThing()`
//  (the return value)
//- t
Thing t(calculateThing());

All three objects may be the same object if copy elision occurs.

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227608

It will work, because (at least semantically), you are returning a copy of the variable to the caller. Now, the actual copy might be elided via return value optimization, so in this kind of expression

Thing t = calculateThing();

the thing from the function body would usually get constructed into the location of t. But t is effectively a copy of thing in the sense that it has the same value.

Upvotes: 1

Related Questions