2

In this code:

RationalNum operator+(const RationalNum& left, const RationalNum& right) {
    RationalNum temp;
    /*code here*/
    return temp;
}

How can it return a RationalNum object if the object is "deleted" from the stack when this function exits?

6
  • 3
    Make sure your RationalNum class follows the rule of 3 /5 /0. Commented Jan 29, 2018 at 21:41
  • @FredyR4zox, objects are not deleted in stack, but they are destructed when they are out of scope? Commented Jan 29, 2018 at 21:42
  • 1
    Cannot reproduce wandbox.org/permlink/BpySBdLYWcvRYBn0 Commented Jan 29, 2018 at 21:46
  • 3
    How can it return a RationalNum object if the object is "deleted" -- The same way that int foo() { int i = 10; return i;} returns 10, even though "i" is "deleted". Commented Jan 29, 2018 at 21:48
  • 2
    Since this is a by-value return, there's no problem here. In fact, with NRVO, chances are good that temp will never actually be created in the function's stack frame at all. If you were returning a pointer or reference, you'd be in deep doo doo. Commented Jan 29, 2018 at 21:49

1 Answer 1

7

It is because the return value is copied (if necessary) before local variables are destroyed. And destroying the returned object is the duty of the calling function.

The returned object is constructed at the point of the return statement but the destruction of locals is left until the end of the block (which comes after the return).

Sign up to request clarification or add additional context in comments.

3 Comments

Note that this is a copy elision context
"copied" or "moved" or "constructed elsewhere on the stack, because it is known the variable will be returned".
Thank you all :) I understood :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.