C ++:对“超出范围”的引用目的 [英] C++: Reference to "out of scope" object
问题描述
关于参考文献我一无所知,希望对我有所帮助。就我所知,引用不能为空。但是,如果您有一个函数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();
理论上的引用将引用一个不存在的对象,因为一旦函数返回,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.
这篇关于C ++:对“超出范围”的引用目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!