删除后可以使用C++成员吗?

0 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

GWW*_*GWW 12

您正在做的是您正在访问已删除对象的未定义行为.您正在查看的数据仍然可用,存储该信息的内存区域尚未被覆盖,但没有任何事情可以阻止这种情况发生.

  • 将指针删除或释放后简单地将指针置零是一种很好的做法. (4认同)