Search code examples
c++linked-listthisdestructorself-destruction

Is it OK to use "delete this" to delete the current object?


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?


Solution

  • 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;
      }
    }