c++ - 为什么访问已删除的对象不会使我的程序崩溃?

标签 c++ memory-management

<分区>

我有一段代码可以创建基于图 block 的关卡。

class Level {

//Variables
//===================================================
public:
    Tile *** TileGrid;  //A 2d array of pointers to tiles
    int TilesWide, TilesTall;

//Methods
//===================================================
public:
    Level::Level(char * fileName);
    Level::~Level();
    void Draw();
};

我为 TileGrid 分配内存,一切正常。我也为该类设置了一个析构函数。

Level::~Level() {

    for (int i = 0; i < TilesTall; i++) {
        for (int j = 0; j < TilesWide; j++)
            //delete the looped tile being pointed to
            delete TileGrid[i][j];

        //delete the row
        delete [] TileGrid[i];
    }

    //delete the array of rows
    delete [] TileGrid;
}

为了咯咯笑,我决定删除关卡实例。这样做之后,我发现我仍然可以调用它的 Draw 方法。

在调试器中,TilesWide 和 TilesTall 的值是一个巨大的负数,因此我的 for 循环迭代网格时没有绘制任何内容。

尝试访问已删除的变量不会导致某种崩溃吗?

最佳答案

它不会一定导致崩溃。它可能会,也可能不会。它会导致所谓的未定义行为:

undefined behaviour
behavior for which this International Standard imposes no requirements

它可能会崩溃,就像毁灭宇宙一样。

关于c++ - 为什么访问已删除的对象不会使我的程序崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14862297/

相关文章:

c++ - 将功能添加到窗口顶部的主菜单

c++ - 我可以将 C++17 无捕获 lambda constexpr 转换运算符的结果用作函数指针模板非类型参数吗?

c++ - 有效 C++ : Item 52 and how to avoid hiding all normal operator new & delete versions

c++ - 什么决定了堆内存的分配位置?

c++ - 如何就地扩展分配的内存

c++ - Qt 中的正则表达式不匹配它应该匹配的字符串

c++ - "most important const"与 auto_ptr : Why the code does not compile?

c++ - 为什么这个变量需要是静态的?

c++ - 写访问冲突 this->head 在 pop_front 中是 0xDDDDDDDD

android - 如何清理位图资源