链表析构函数

Linked list destructor

本文关键字:析构函数 链表      更新时间:2023-10-16

我在自己的时间里学习C++,并编写了一个链表来尝试掌握它的窍门。我很担心删除对象的方法。这是一个单独链接的列表。这是析构函数:

template <typename T>
LinkedList<T>::~LinkedList() 
{
  Node<T> * current = this->first;
  do {
    Node * temp = current->next;
    delete current; // THIS JUST MIGHT BE A TERRIBLE IDEA!!!
    Node * current = temp; // new current-- might work with the current
                           // delete a line above
  } while (current->next != 0); // need to leave this->last so that I don't
                                // delete it twice in the next line.
                                // Just realized I'm deleting this->first, then 
                                // in the next line [implicitly] deleting it again!
                                // 
  delete this;
}

创建指向列表中第一个节点的指针,创建指向下一个节点的临时指针,删除第一个指针,创建一个同名的新指针,然后循环返回。完成后,它将删除"this"指针。

我相信你可以理解为什么我对创建一个与已删除指针同名的新指针的方式感到担忧。

  1. 不要在析构函数中delete this
  2. 如果Node是一个模板,那么您需要在所有这些定义中写入Node<T>
  3. 不要重新定义current,只需为其指定一个新值即可

除此之外,我在这个片段中没有看到任何其他问题。

为什么不编译代码,尝试一下,看看会发生什么?最糟糕的事情是你的程序崩溃了,你必须弄清楚原因。

您的代码基本上应该可以工作,除了您需要在while循环条件中测试current而不是current->next,并且在析构函数中写入delete this是多余的(可能是错误的(,Cat Plus Plus在他的回答中指出了更多的错误。

如果你正在尝试学习C++,那么你应该更多地学习它,直到你理解你在这里犯的错误,并相信修复的代码会起作用。

这是我的固定版本的功能:

template <typename T> LinkedList<T>::~LinkedList() 
{
    Node<T> * current = this->first;
    while(current != 0) {
        Node<T> * temp = current->next;
        delete current;
        current = temp;
    }
    delete this;
}

我没有看到问题,但我看到了很多错误:

template <typename T>
LinkedList<T>::~LinkedList() 
{
    Node<T>* current = this->first; // you never check if this->first is 0
    do {
        Node * temp = current->next;
        delete current; // THIS is not a problem
        Node * current = temp; /* this line has no effect -
                     you define new variable and it disappears when reaches
                     the end of its scope next line */
    } while (current->next != 0); /* 'current' is always 'this->first' but
              even if you would assign it 'temp' like you intended few lines
              above you never check if 'current' is 0 so you will
              dereference 0 when you reach the end of the list */
    delete this; /* this line is total nonsense
            if your LinkedList is created with 'new LinkedList' then
            you have infinite recursion (you call destructor from destructor)
            otherwise you 'delete' pointer that you never 'new'-ed */
}

正确的代码是:

template <typename T>
LinkedList<T>::~LinkedList() 
{
    Node<T>* current = this->first;
    while (current != 0)
    {
        Node<T>* temp = current->next;
        delete current;
        current = temp;
    }
}
~LinkedList
{
//...
  delete this;
}

析构函数中的delete this;就像代码自杀。您的对象已经被破坏,而您再次使用delete this;进行破坏。这是一种未定义的行为。你可以删除它。其余的看起来不错(假设this->first给头部Node(。

编辑:我错过了,你重新定义了current。把它取下来。(应简称为current = temp;(