gpt4 book ai didi

c++ - 删除指针时程序崩溃

转载 作者:行者123 更新时间:2023-11-28 00:16:39 25 4
gpt4 key购买 nike

大家好我的代码是:

class aClass
{
public:
int data;
aClass* pointer=NULL;

aClass(int x): data(x) {
cout << "calling int constructor\n";
}

~aClass() {
delete pointer;
cout <<"Index " <<this->data<<" calling destructor\n";
}
};

int main()
{
aClass ob1(1);
ob1.pointer=new aClass(2); // let's say the new object is called ob2
ob1.pointer->pointer=new aClass(3);// let's say the new object is called ob3
delete ob1.pointer; //destory ob2, which will destory ob3 in sequentially.
return 0;
}

我期望输出是这样的:

calling int constructor
calling int constructor
calling int constructor
Index 2 calling destructor
Index 3 calling destructor //I think when ob2is destoyed ob3 will be destoyed
//too, but this is not in the output even though I delete "delete pointer" in
//the destructor
Index 1 calling destructor

但是程序崩溃了,我知道它在使程序崩溃的析构函数中的“删除指针”,但我不知道为什么会崩溃,为什么ob3没有被销毁?

最佳答案

当退出main时,ob1被自动销毁,所以它的析构函数被调用。 pointer 再次被删除,导致崩溃。不要手动删除 ob1.pointer

这是一个基本示例,可帮助您了解正在发生的事情。

class C
{
public:
C* p;

C() : p(NULL)
{}

~C()
{ delete p; }
};

int main()
{
C a;
// ...

// Lets say a.p == 5 for some reason.
delete a.p;
// The memory at address 5 is now deleted, but a.p remains unchanged.
// a.p is still 5, but accessing it is now illegal.

return 0;
// Stack cleanup -> a is destroyed.
// a´s destructor is called, which attempts to delete its p.
// This p is a.p which was deleted earlier.
// Remember, a.p is still 5, and now it is deleted in ~C.
// -> You deleted the memory at address 5 twice.
}

关于c++ - 删除指针时程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29841125/

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