1

我试过下面的C++代码

#include <iostream>
using namespace std;

int main()
{
    int *p = new int;
    *p = 10;
    int &a = *p;
    delete p;
    a = 20;
    cout<<a<<" ";
    cout<<*p;
    return 0;
}

并得到输出:20 20

我认为这可能会由于访问释放的内存或一些垃圾而导致运行时错误。可能我得到了这个输出,因为程序释放的内存位置到目前为止可能还没有使用,所以仍然保留旧值。

所以我认为如果我不使用引用也应该发生

#include <iostream>
using namespace std;

int main()
{
    int *p = new int;
    *p = 10;
//  int &a = *p;
    delete p;
//  a = 20;
//  cout<<a;
    cout<<*p;
    return 0;
}

但在这种情况下,我得到的输出为 0(通过多次运行检查)。Reference 是否与不同的输出有关?

编译器:gcc 版本 4.7.2 (Ubuntu/Linaro 4.7.2-2ubuntu1)

4

2 回答 2

2

您正在取消引用已释放的内存。这是未定义的行为。无法保证结果会是什么。碰巧结合编译器、操作系统和 C++ 库,程序似乎可以工作。

This is one possible outcome of undefined behaviour.

于 2013-02-16T15:45:48.310 回答
1

Dereferencing delete-d memory is undefined behaviour and there's no point figuring out some patterns as switching to another compiler or another release of the same compile could break it.

delete calls destructors of non-primitive types. If you have a class Integer wrapper that clears the content when destroyed, you'll see some difference. On primitive types, delete does not re-initialize the space released. Therefore you might see the original value retained but this is not guaranteed to work at all and you should never rely on it.

于 2013-02-16T15:57:17.890 回答