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++:对“超出范围"的引用目的
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07