gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:37:30 27 4
gpt4 key购买 nike

我编译并运行了下面粘贴的代码,令人惊讶的是它没有错误。 (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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com