C++ 删除 - 它删除了我的对象,但我仍然可以访问数据? [英] C++ delete - It deletes my objects but I can still access the data?

查看:41
本文介绍了C++ 删除 - 它删除了我的对象,但我仍然可以访问数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的俄罗斯方块游戏,其中每个块都是单块类的一个实例.

I have written a simple, working tetris game with each block as an instance of a class singleblock.

class SingleBlock
{
    public:
    SingleBlock(int, int);
    ~SingleBlock();

    int x;
    int y;
    SingleBlock *next;
};

class MultiBlock
{
    public:
    MultiBlock(int, int);

    SingleBlock *c, *d, *e, *f;
};

SingleBlock::SingleBlock(int a, int b)
{
    x = a;
    y = b;
}

SingleBlock::~SingleBlock()
{
    x = 222;
}

MultiBlock::MultiBlock(int a, int b)
{
    c = new SingleBlock (a,b);
    d = c->next = new SingleBlock (a+10,b);
    e = d->next = new SingleBlock (a+20,b);
    f = e->next = new SingleBlock (a+30,b);
}

我有一个函数可以扫描整行,并遍历块的链表,删除相关块并重新分配 ->next 指针.

I have a function that scans for a complete line, and runs through the linked list of blocks deleting the relevant ones and reassigning the ->next pointers.

SingleBlock *deleteBlock;
SingleBlock *tempBlock;

tempBlock = deleteBlock->next;
delete deleteBlock;

游戏运行正常,块被正确删除,一切都按预期运行.但是经过检查,我仍然可以访问已删除数据的随机位.

The game works, blocks are deleted correctly and everything functions as it is supposed to. However on inspection I can still access random bits of deleted data.

如果我在删除后打印每个已删除的单块x"值,其中一些返回随机垃圾(确认删除),其中一些返回 222,即使析构函数被称为数据不是实际上是从堆中删除的.许多相同的试验表明,没有正确删除的总是相同的特定块.

If I printf each of the deleted singleblocks "x" values AFTER their deletion, some of them return random garbage (confirming the deletion) and some of them return 222, telling me even though the destructor was called the data wasn't actually deleted from the heap. Many identical trials show it is always the same specific blocks that are not deleted properly.

结果:

Existing Blocks:
Block: 00E927A8
Block: 00E94290
Block: 00E942B0
Block: 00E942D0
Block: 00E942F0
Block: 00E94500
Block: 00E94520
Block: 00E94540
Block: 00E94560
Block: 00E945B0
Block: 00E945D0
Block: 00E945F0
Block: 00E94610
Block: 00E94660
Block: 00E94680
Block: 00E946A0

Deleting Blocks:
Deleting ... 00E942B0, X = 15288000
Deleting ... 00E942D0, X = 15286960
Deleting ... 00E94520, X = 15286992
Deleting ... 00E94540, X = 15270296
Deleting ... 00E94560, X = 222
Deleting ... 00E945D0, X = 15270296
Deleting ... 00E945F0, X = 222
Deleting ... 00E94610, X = 222
Deleting ... 00E94660, X = 15270296
Deleting ... 00E94680, X = 222

是否能够从坟墓之外访问数据?

抱歉,有点啰嗦.

推荐答案

是否能够从坟墓之外访问数据?

Is being able to access data from beyond the grave expected?

这在技术上称为未定义行为.如果它也为您提供一罐啤酒,请不要感到惊讶.

This is technically known as Undefined Behavior. Don't be surprised if it offers you a can of beer either.

这篇关于C++ 删除 - 它删除了我的对象,但我仍然可以访问数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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