c++ - 删除链表

标签 c++ linked-list

嘿,我想知道 我写了一个 C++ 链表,我在其中调用析构函数来遍历分配的链表并删除找到的每个节点。然而我发现,尽管它遍历链表并删除每一次出现,它仍然会打印出值。尽管只是一些报废值(value)。

但是,当我删除 linked_list 时,它不应该在下次打印吗? 我使用 new 创建一个链接列表,当我删除列表时使用 delete

sorted_list::~sorted_list()
{
    // Destructor implementation
    destroy(this->first);
    cout << "Destructor called sorted_list" << endl;
}

void sorted_list::destroy(list_link* item)
{
  if (item)
  {
    destroy(item->next);
    delete item;
  }
}

打印函数

void sorted_list::print() {

    if(this->first)
    {
        iteratorn *traverse = new iteratorn(this->first);
        while( !traverse->iterator_end() )
        {
            cout << traverse->iterator_get_key() << " ";
            traverse->iterator_next();
        }
        delete traverse;
    }
    else
        cout << "list empty" << endl;
}

最佳答案

当你访问一个被破坏的对象时,行为是未定义的。事实上,删除一个对象并不会清除内存,只是将其标记为可用,所以如果你对已经删除的对象执行一些操作,它们可能会做一些合理的事情。但同样,该对象已被破坏,因此您不能访问它。

当然,在链表被析构后,你不应该保留任何指向属于链表的对象的指针,因为这些对象也会被析构。

顺便说一下,您的 sorted_list::destroy 是递归的,效率很低。您可能需要用迭代方法替换它:

void sorted_list::destroy(list_link* item)
{
    while (item)
    {
        list_link* old = item;
        item = item->next;
        delete old;
    }
}

(你应该考虑@Roger Pate 的评论,不要在调用 destroy(this->first); 后第二次删除 this->first。)

关于c++ - 删除链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4112905/

相关文章:

c++ - 澄清 C++ 中的引用

python - 有什么方法可以将用C++创建的变量加载到python解释器中吗?

c - 链接列表元素未显示

c++ - 将节点添加到链表的前面,然后计算链表中的节点数

c++ - 如何在第一次出现 x(线性链表)C++ 后添加新元素 y

c++ - C++ 中的嵌入式资源

c++ - 带有模板的基于枚举的工厂无法转换类型

c++ - 如何在 C++ 中同时写入和读取文件

c - 从文件中读取日语字符的问题 - C

c++ - 如何将 find_if 与链表等非容器一起使用?