C++:对“超出范围"的引用目的
关于引用,我从未理解一件事,我希望有人能帮助我.据我所知,引用不能为空.但是如果你有一个函数 foo() 返回一个对堆栈对象的引用会发生什么:
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();
理论上的 ref 将引用一个不存在的对象,因为 o 一旦函数返回就超出范围.这里发生了什么?
Theoretical ref would refer to an non existing object since o runs out of scope as soon as the function returns. Whats happening here?
推荐答案
这会导致未定义的行为.不要这样做.
This causes undefined behaviour. Don't do it.
在实现方面,实际上,引用将指向过去调用 foo
的堆栈帧所在的堆栈.该记忆在许多情况下仍然有意义,因此错误通常不会立即显现.因此,您应该注意永远不要做这样的悬空引用.
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.
相关文章