C++ 成员在删除后可用吗?

标签 c++ class delete-operator

我编译并运行了下面粘贴的代码,令人惊讶的是它没有错误。 (g++/Linux) 已删除的对象如何让一些成员仍然可用?这是正常行为吗?

#include <iostream>

using namespace std;

class chair {
    public:
    int height;
    int x;
    int y;

    chair() {
        before = last;
        if(last!=NULL)
            last->after = this;
        else
            first = this;
        last = this;
        after = NULL;
    }

    ~chair() {
        if(before != NULL)
            before->after = after;
        else
            first = after;
        if(after != NULL)
            after->before = before;
        else
            last = before;
    }

    chair* before;
    chair* after;
    static chair* first;
    static chair* last;
};
chair* chair::first;
chair* chair::last;

int main() {
    chair *room = NULL;
    int tempx = 0;
    int tempy = 1;

    while(tempx<=3) {

        tempy = 1;
        while(tempy<=3) {
            room = new chair();
            room->x = tempx;
            room->y = tempy;
            tempy++;
        }

        tempx++;
    }

    room = chair::first;
    while(room!=NULL) {
        cout << room->x << "," << room->y << endl;
        delete room;
        room = room->after;
    }
}

最佳答案

你正在做的是 undefined behavior 您正在访问已删除的对象。您正在查看的数据仍然可用,并且存储该信息的内存区域尚未被覆盖,但没有什么能阻止这种情况发生。

关于C++ 成员在删除后可用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5175414/

相关文章:

c++ - 使用 Qt 在 C++ 中自定义 UI?

javascript - 间接调用函数时成员未定义

c++ - 我的 C++ 函数在不应该的时候破坏了变量

c++ - 删除数组内对象内的动态分配对象

c++ - 未定义的新运算符如何导致 C++ 中的未定义行为?

c++ - Xercesc XPath 功能

c++ - 在 Ubuntu 64 位操作系统中无法读取大于 2GB 的文件

c++ - 如果可以将其置于私有(private)状态,为什么还要使用 static const (int/string/..)?

c++ - 谷歌模拟 ByRef 方法

c++ - 为什么分配成员会引发 NullReferenceException?