当C ++参考离开其范围时会发生什么? [英] What happens when C++ reference leaves its scope?

查看:76
本文介绍了当C ++参考离开其范围时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我正确解释C ++引用,它们就像指针,但具有保证的数据完整性(无NULL,无(int *)0x12345)。但是,如果离开引用对象的范围,会发生什么呢?如果不涉及任何魔术(可能没有),引用的对象将在我的背后被销毁。

If I interpret C++ references correctly, they are like pointers, but with guaranteed data integrity (no NULL, no (int*) 0x12345). But what happens when scope of referenced object is leaved? If there are no magic involved (and probably it is not), referenced object will be destroyed behind my back.

我写了一段代码来检查:

I wrote a piece of code to check this:

#include <iostream>
using namespace std;

class A {
public:
        A(int k) { _k = k; };
        int get() { return _k; };
        int _k;
};

class B {
public:
        B(A& a) : _a(a) {}
        void b() { cout << _a.get(); }
        A& _a;
};

B* f() {
        A a(10);
        return new B(a);
}

int main() {
        f()->b();
}

_k 实例

令人惊讶的是,它没有分段错误,而是正确打印了 10,而我认为 A 是在堆栈上分配的,而 f()的堆栈框架将至少被 cout<< 调用。

It surprisingly does not segfault and instead prints '10' correctly, while I suppose that A is allocated on stack and that stack frame of f() will be overwritten by at least cout<< call.

推荐答案

这是未定义的行为,您很幸运地发现的内存一个尚未用于其他任何用途。在更复杂的情况下,几乎可以肯定会得到垃圾。在我的机器上,此代码会产生随机垃圾。对我来说,这可能是因为我使用的是使用寄存器调用约定的64位计算机。寄存器比主存储器更经常地被重复使用(理想情况下是……)。

this is undefined behavior and you were simply lucky that the memory for a hadn't been used for anything else yet. In a more complex scenario you would almost certainly get garbage. On my machine I get random garbage with this code. For me, this is likely because I am using a 64-bit machine which uses a register calling convention. Registers get re-used much more often than main memory (ideally...).

因此,回答发生了什么的问题。在这种情况下,引用可能只是语法更友好的有限指针:-)。在 a 的地址下存储。后来 a 对象超出范围,但 B 对象对该 a <的引用/ code>不会自动更新以反映这一点。因此,您现在有一个无效的引用。

So to answer your question of "what happens". Well in this scenario, the reference is likely little more than a limited pointer with friendlier syntax :-). Under the hood the address of a is stored. Later the a object goes out of scope, but the B object's reference to that a will not be "auto-magically" updated to reflect this. Hence you have an invalid reference now.

使用此无效引用将产生几乎所有内容,有时会崩溃,有时甚至会产生大量数据。

Using this invalid reference will yield just about anything, sometimes crashes, sometimes just bunk data.

编辑:由于Omnifarious,我一直在考虑这一点。在c ++中有一条规则基本上说:如果您有一个const引用到一个临时对象,那么该临时对象的生存期至少与const引用一样长。引入了一个新问题。

Thanks to Omnifarious, I've been thinking about this. There is a rule in c++ that basically says that if you have a const reference to a temporary, then the lifetime of the temporary is at least as long as the const reference. Which introduced a new question.

编辑:对有兴趣的人(对临时奇数的常量引用

这篇关于当C ++参考离开其范围时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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