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++:对“超出范围"的引用目的


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01