7

There is one thing I never understood about references and I hope that one might help me. For all I know, a reference cannot be null. But what happens if you have a function foo() returning a reference to an stack object:

Object & foo(){
    Object o;
    return o;
}

Object & ref = foo();

Theoretical ref would refer to an non existing object since o runs out of scope as soon as the function returns. Whats happening here?

Sebastian Hoffmann
  • 11,127
  • 7
  • 49
  • 77
  • 2
    A null pointer is not the same thing as an invalid pointer! – leftaroundabout Mar 30 '12 at 10:49
  • To clarify - nothing prevents a reference from being `null`. You just can't take a reference to `null` directly. – Konrad Mar 30 '12 at 11:01
  • Even in practice, `ref` would refer to a non-existing object, as would the phrase "the present king of France". – molbdnilo Mar 30 '12 at 11:37
  • possible duplicate of [What happens when C++ reference leaves it's scope?](http://stackoverflow.com/questions/3097593/what-happens-when-c-reference-leaves-its-scope) – Calimo Apr 04 '14 at 07:40

3 Answers3

12

This causes undefined behaviour. Don't do it.

Implementation-wise, realistically, the reference would point into the stack where the stackframe for the call to foo used to be. That memory will in many cases still make sense, so the error is often not immediately apparent. Therefore, you should take care never to make a dangling reference like that.

Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82
1

nothing before you use the returned reference - then you'll be reading/writing over your stack

Ventsyslav Raikov
  • 6,882
  • 1
  • 25
  • 28
1

The behaviour in this context is undefined - this isn't particularly odd in c++. This is essentially identical to the situation where you have a pointer set to a local variable which has gone out of scope. C++ requires YOU control handle references and the lifetime of referenced objects.

Elemental
  • 7,365
  • 2
  • 28
  • 33