Is the code below legal?
int foo()
{
int local = 5;
int& local_ref = local;
return local_ref;
}
If yes, then it's most likely will copy value of local
to the return value before destroying local
, but why? Neither GCC nor MSVC doesn't complain about this, so probably it's legal... isn't it?
Its valid. The value is copied before both local
and local_ref
goes out of scope. On the other hand, returning local reference would invoke undefined behavior. By local reference, i mean int& foo()
, not the variable local_ref
.
Before function is called, the stack frame is created (space on stack for parameters, return value and as part of it, the current program counter is saved). Then during function execution, local variables (local
and local_ref
) are constructed on stack. Before program counter leave the scope of function, the return value (value
) is copied to the functions stack frame and after this, program counter returns to the position stored in stack frame (from where foo
was called).
For more information search for stack frame.