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?
Henri Menke
11k1 gold badge27 silver badges45 bronze badges
1 Answer 1
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).
answered Jan 29, 2018 at 21:48
SoronelHaetir
15.5k1 gold badge18 silver badges26 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
M.M
Note that this is a copy elision context
Drew Dormann
"copied" or "moved" or "constructed elsewhere on the stack, because it is known the variable will be returned".
FredyR4zox
Thank you all :) I understood :)
lang-cpp
RationalNumclass follows the rule of 3 /5 /0.deleted in stack, but they are destructed when they are out of scope?int foo() { int i = 10; return i;}returns10, even though "i" is "deleted".tempwill 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.