-1

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?

r5ha
  • 332
  • 5
  • 13
  • 4
    Its correct. The value is copied. On the other hand, returning local reference would invoke undefined behavior. By local reference, i mean `int& foo()`, not the variable `local_ref`. – kocica Jul 30 '18 at 09:25
  • Your function returns `int`, not `int&`, and thus you are not returning a reference. So, you would need to rephrase your question like _Is it undefined to return a copy of a function-scope variable_, and then you would immediately see that is is not really a question. – Adrian W Jul 30 '18 at 10:14

1 Answers1

0

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.

kocica
  • 6,412
  • 2
  • 14
  • 35