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?
Yes. It should be perfectly fine. "This" is just a pointer. Any pointer will do for delete.
"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.
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).
“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.
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With