0

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?

Community
  • 1
  • 1
user997112
  • 29,025
  • 43
  • 182
  • 361

3 Answers3

1

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.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

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.

masoud
  • 55,379
  • 16
  • 141
  • 208
  • Our of curiosity, could you elaborate in depth on your point about "new/delete stuffs in Thing"? – user997112 Mar 10 '13 at 21:40
  • It's long to tell in comments. Read this [tutorial](http://www.codeproject.com/Tips/78946/C-Copy-Constructor-in-depth). – masoud Mar 10 '13 at 21:45
  • 1
    @user997112 be aware that return value optimization (see my answer) means that in actual fact, it is most likely that the `thing` in the function **will not** be destroyed when the function returns, but rather, `new_thing` and `thing` will be one and the same object. This is important to consider because often people get worried about the cost of copying when returning by value, but with RVO there is no cost. – juanchopanza Mar 10 '13 at 22:07
0

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.

Mankarse
  • 39,818
  • 11
  • 97
  • 141