2

当我尝试以下代码时,似乎“删除”(C++ 中的空闲内存)不起作用......好吧,我知道该引用不适合“引用稍后将被释放的对象”。我只是在玩代码..

class A{
public:
    int val;
    A(int val_=0):val(val_){}
};

A* ptrA = new A(10);
A &refA = *ptrA;
printf("%d\n", refA.val);
delete ptrA;
refA.val = 100;
printf("%d\n", refA.val);

输出为:10 100

4

3 回答 3

8

确实有效,并且您所做的一切都会refA导致未定义的行为,即,就标准而言,任何事情都可能发生,包括“它似乎有效”。

在实践中,目前它似乎可以工作,因为该内存还没有被重用,但是等待一些分配,你会发现你将覆盖其他不相关的对象。

请记住,当您进入“未定义行为”时,如果幸运的话,您会遇到崩溃或断言失败;通常,您会遇到奇怪的、不可重现的错误,这些错误偶尔会让您发疯。

好吧,我知道引用不适合“引用稍后将被释放的对象”。我只是在玩代码..

引用将被释放的东西并没有什么不好……重要的是,它必须在引用超出范围后被释放。例如,在这种情况下它非常好:

A* ptrA = new A(10);
{
    A &refA = *ptrA;
    std::cout<<refA.val<<"\n";
}
delete ptrA;
于 2012-12-23T17:29:38.927 回答
2

好吧,我知道引用不适合“引用稍后将被释放的对象”

Actually it appears you don't quite understand that yet. When people say this, it does not mean that if you try to do it, an error or similar will occur. It means that all bets are off and anything can happen. "Anything" includes the behaviour you observed.

This is why you should not do it: you have no guarantee whatsoever about what may happen, so it basically amounts to programming by gambling.

于 2012-12-23T17:31:43.577 回答
1

The object is deleted and your code results in an undefined behavior. In your specific case it outputs what you want, but that shall not work and will not work in general case.

于 2012-12-23T17:34:19.417 回答