Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++成员删除后可用?_C++_Class_Delete Operator - Fatal编程技术网

C++成员删除后可用?

C++成员删除后可用?,c++,class,delete-operator,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)

我编译并运行了粘贴在下面的代码,令人惊讶的是,它没有出现错误。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;
    }
}
您所做的是访问已删除的对象。您正在查看的数据仍然可用,并且存储该信息的内存区域尚未被覆盖,但没有任何东西阻止这种情况的发生。

delete不会更改指针变量本身,因此它仍然指向旧的内存位置


您可以尝试访问该内存位置,但在删除了该位置的对象后,您是否会在该位置找到有用的内容,这取决于您的运气。通常这是未定义的行为。

通过调用delete,您只是告诉程序您不再需要该内存块。然后它就可以随心所欲地使用那个内存了,在你的例子中,它还不需要那个内存,所以它就保持原样了。稍后,您的程序可能会使用该内存块,如果您继续访问它,您将获得垃圾数据


删除或释放指针后,简单地将其归零始终是一种很好的做法。@M.Tibbits:我完全同意我一直有这样做的习惯。任何好的内存管理器都会在调试构建中使用类似0xdd的独特模式来设置整个释放的内存块,以使指针查找很可能崩溃。@EboMike:这很好,我从来没有这样做过以前听说过。是的,这是一个很好的功能,我记得在用Borland C++Builder调试时,内存管理器会用0xBAADF00D填充所有32位DWORD,当在断点转储内核时,您可以立即发现错误。