Reputation: 11482
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?
Upvotes: 6
Views: 2166
Reputation: 7491
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.
Upvotes: 1
Reputation: 7192
nothing before you use the returned reference - then you'll be reading/writing over your stack
Upvotes: 1
Reputation: 22089
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.
Upvotes: 11