0

Consider:

int & foo () {
    int b = 2;
    return b;
}

int main() {
    int a = foo();
    std::cout << "a: " << a << std::endl;
}

Foo returns reference to variable b, which is out of scope of main. The cout prints 2. Does this mean that a copy of b is created? Or is it that lifetime of b is extended to the lifetime of a?

Mykybo
  • 1,429
  • 1
  • 12
  • 24
  • Because C++ won't stop you from shooting yourself in the foot. You need to know what you are doing. Yes, it isn't safe, but oh so powerful. – StoryTeller - Unslander Monica Mar 19 '17 at 14:48
  • has been answered here http://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable – Ap31 Mar 19 '17 at 14:51
  • You may find your answer [here](http://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable) – Jiahao Cai Mar 19 '17 at 14:52
  • 2
    @Ap31 I disagree, I have already read that. What the answer there says is "will not work because you're returning an alias (a reference) to an object with a lifetime limited to the scope of the function call". However, it works, and I am asking how.. – Mykybo Mar 19 '17 at 14:54
  • 2
    @Mykybo Undefined Behaviour means that sometimes things can appear to work, but this is by chance only. In this case the returned reference is referencing a position in the stack that no longer contains valid data, it is just chance that the value at this position has not yet been overwritten. – Richard Critten Mar 19 '17 at 14:57
  • @Mykybo well I guess the answer might be clearer on the part of what "will not work" means. And it means UB, which could result in any behavior, including what you observe. – Ap31 Mar 19 '17 at 15:04

0 Answers0