Destruct Run Time错误

时间:2014-06-09 16:28:56

标签: c++

我编写了一个带有函数的linkelist代码,将一个链表附加到另一个,但是当析构函数调用它时会导致运行时错误

这是代码

class doublelist
{
private :
    doublelist *L;
    doublelist *next;
    double x;
public:
    doublelist(double x[], int size)
    {
        if (!x)return;
        L = new doublelist();
        L->x = x[0];
        L->next = NULL;
        doublelist *temp = L;
        for (int i = 1; i < size; i++)
        {
            temp->next = new doublelist();
            temp = temp->next;
            temp->x = x[i];
            temp->next = NULL;
        }
    }
    ~doublelist()
    {
        doublelist *temp = L;
        while (temp)
        {
            delete temp;
            cout << temp;
            temp = temp->next;
            temp = L;
        }
    }
};
void main()
{
    double a[] = { 3, 2, 5, 6, 1, 7 };
    doublelist me(a, 6);
    double b[] = { 10, 213, 4 };
    me.append(doublelist(b, 3));
    me.print();
    system("pause");
}

哦,对不起..我试图修复代码,但我不能在这里是破坏者

~doublelist()
{
    doublelist *temp = L;
    while (temp)
    {
        L = L->next;
        delete temp;
        temp = L;
    }
}

1 个答案:

答案 0 :(得分:4)

在析构函数中查看此代码:

delete temp;       // calling delete 
cout << temp;
temp = temp->next; // using a pointer that has been deleted. 

调用delete是你可以用指针做的最后一件事(安全)。