Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 244
jkeys Avatar asked Aug 11 '09 01:08

jkeys


People also ask

Is delete this safe?

Yes. It should be perfectly fine. "This" is just a pointer. Any pointer will do for delete.

What does delete this do?

"delete this" in C++? Delete is an operator that is used to Deallocate storage space of Variable. This pointer is a kind of pointer that can be accessed but only inside nonstatic member function and it points to the address of the object which has called the member function.

What happens if we delete this pointer?

The address of the pointer does not change after you perform delete on it. The space allocated to the pointer variable itself remains in place until your program releases it (which it might never do, e.g. when the pointer is in the static storage area).

Is delete this valid C++?

“delete this” in C++ 1) delete operator works only for objects allocated using operator new (See this post). If the object is created using new, then we can do delete this, otherwise behavior is undefined.


2 Answers

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;
  }
}
like image 119
Brian R. Bondy Avatar answered Oct 13 '22 22:10

Brian R. Bondy


No you should not delete this from the destructor. The destructor gets called because of a delete statement (or goes out of scope) and this would most likely lead to some sort of crash.

You also have a couple problems in the DoublyLinkedList desturctor. One, you delete temp then access temp after its been deleted. Second, the code will not actually delete the last element in the linked list.

like image 43
Brian Ensink Avatar answered Oct 14 '22 00:10

Brian Ensink