是否可以使用"删除此项"删除当前对象?

jke*_*eys 7 c++ destructor linked-list this self-destruction

我正在编写一个链表,我想要一个struct的析构函数(一个Node结构)来简单地删除它自己,并且没有任何副作用.我希望我的列表的析构函数迭代地自己调用Node析构函数(临时存储下一个节点),如下所示:

//my list class has first and last pointers
//and my nodes each have a pointer to the previous and next
//node
DoublyLinkedList::~DoublyLinkedList
{
    Node *temp = first();

    while (temp->next() != NULL)
    {
        delete temp;
        temp = temp->next();
    }
}
Run Code Online (Sandbox Code Playgroud)

所以这将是我的Node析构函数:

Node::~Node
{
   delete this;
}
Run Code Online (Sandbox Code Playgroud)

这是否可以接受,特别是在这种情况下?

Bri*_*ndy 17

如果正在调用Node析构函数,那么它已经被删除了.因此删除在Node析构函数中没有意义.

这也是错的:

while (temp->next() != NULL)
{
     delete temp;
     temp = temp->next();
}
Run Code Online (Sandbox Code Playgroud)

相反,你应该将temp-> next()转换为临时变量.否则您正在访问已删除的内存.

所以更像这样:

DoublyLinkedList::~DoublyLinkedList
{
  Node *temp = first();
  while (temp != NULL)
  {
       Node *temp2 = temp->next();
       delete temp;
       temp = temp2;
  }
}
Run Code Online (Sandbox Code Playgroud)