删除指针时程序崩溃

时间:2015-04-24 07:20:28

标签: c++

大家好我的代码是:

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

但程序崩溃了,我知道&#34;删除指针&#34;在破坏程序的析构函数中,但是我不知道它为什么崩溃以及为什么ob3不会被破坏?

1 个答案:

答案 0 :(得分:3)

退出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.
}