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?
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:
Instead you should get temp->next() into a temp variable. Otherwise you are accessing deleted memory.
So more like this:
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.