C++: Reference to quot;out of scopequot; object(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.
这篇关于C++:对“超出范围"的引用目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++:对“超出范围"的引用目的


- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- C++ 协变模板 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01