【问题标题】:Why is my destructor causing an issue with my linked list为什么我的析构函数会导致我的链表出现问题
【发布时间】:2016-06-27 07:55:20
【问题描述】:

我的析构函数:

~list() {
    for (node *p; !isEmpty();) 
    {
        p = head->next;
        delete head;
        head = p;
    }
}

我的函数追加:

void append( list L2)
{

    if (head == 0 && L2.head == 0)
    {
        cout << "Error List Empty" << endl;



    }
    else if (isEmpty())
    {
            L2.printAll();
    }
    else if (L2.isEmpty())
    {
            printAll();  
    }


    else
    {
        tail->next = L2.head;
        tail = L2.tail;
        L2.head = L2.tail = 0;
    }
}

当析构函数试图运行时代码停止。

我的主要:

int main()
{
list l1;
l1.addToHead(1);
l1.addToHead(2);

list l2;
l2.addToHead(9);
l2.addToHead(3);
l2.addToHead(4);

l1.printAll();

cout << "-------------------" << endl;
l2.printAll();

l1.append(l2);

cout << "=============" << endl;

输出: 2 1 斜线 4 3 9 等号线 按任意键继续...

当我没有考虑 l1 为空或 l2 为空等其他条件时,代码运行良好。它将 l2 附加到 l1,并清空 l2。

但现在我试图说明两个列表都为空或一个列表为空,我得到了一个调试断言。看起来析构函数试图运行,然后在“删除头”之前遇到问题

更新--

isEmpty fn:

    int isEmpty() {
    return head == 0;
}

【问题讨论】:

  • 你使用的是内置的拷贝构造函数吗?
  • 但是isEmpty() 是在哪里定义的?这似乎是这里最有可能的失败点。
  • 是的。是 l1.append(l2);这是导致问题的原因吗?
  • 根据您的更新,我猜您的列表实际上已以某种方式损坏。检查您在附加之外定义head-&gt;next 的位置。如果您使用调试器或(可能更容易)调试函数来“遍历”列表,打印headnext 的地址直到到达NULL,这也可能会有所帮助。这应该会告诉你出了什么问题。
  • @JackFaber 我要在这里冒险,建议您阅读What is The Rule of Three?

标签: c++ list linked-list append destructor


【解决方案1】:

我敢打赌,isEmpty 正在检查 head 是否为 NULL,它总是评估为 true,因为你从来没有设置它。

试试这个:

node* p = NULL;

while (head != NULL)
{
    p = head->next;
    delete head;
    head = p;
}

【讨论】:

  • 试过了,还是说:debug assertion fail。 _block_type_is_valid(phead-nblockuse)
【解决方案2】:

我认为 isEmpty() 的返回类型应该是布尔值

bool isEmpty() {
    return head == 0;
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2017-03-23
    • 2013-03-04
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多