Is it OK to use “delete this” to delete the curren

2019-01-15 19:10发布

I'm writing a linked list and I want a struct's destructor (a Node struct) to simply delete itself, and not have any side effects. I want my list's destructor to iteratively call the Node destructor on itself (storing the next node temporarily), like this:

//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();
    }
}

So this would be my Node destructor:

Node::~Node
{
   delete this;
}

Is this acceptable, especially in this context?

8条回答
姐就是有狂的资本
2楼-- · 2019-01-15 19:44

If the Node destructor is being called, then it's already in the process of being deleted. So a delete doesn't make sense inside your Node destructor.

Also this is wrong:

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

Instead you should get temp->next() into a temp variable. Otherwise you are accessing deleted memory.

So more like this:

DoublyLinkedList::~DoublyLinkedList
{
  Node *temp = first();
  while (temp != NULL)
  {
       Node *temp2 = temp->next();
       delete temp;
       temp = temp2;
  }
}
查看更多
你好瞎i
3楼-- · 2019-01-15 19:45

Code above will call Node::~Node() twice. (in "delete temp" and in Node::~Node())

Node::~Node() should not call "delete this" (or your program will crash)

ps. while loop in your code will not work. It will dereference invalid pointer. You should first copy the value of temp->next, and then destroy temp pointer.

查看更多
登录 后发表回答