C++:对“超出范围"的引用目的 [英] C++: Reference to "out of scope" object

查看:19
本文介绍了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++:对“超出范围"的引用目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆