Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Reference to "out of scope" object

Tags:

c++

reference

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?

like image 994
Sebastian Hoffmann Avatar asked Mar 30 '12 10:03

Sebastian Hoffmann


1 Answers

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.

like image 173
Magnus Hoff Avatar answered Sep 19 '22 17:09

Magnus Hoff