So, I'm writing a linked list class, and I have to make a destructor for it...except we never went over how to do it in class and I have no idea if I'm doing it right.
I have a node class that has a working destructor. I've written a destructor for my linked list class that essentially calls the Node Class's destructor for every node in the list....but I have no idea if that's the right way to do it??
Here's what my destructor looks like (I've commented in the Node destructor as well, at the bottom)
DO not call destructors directly. This is rarely need and absolutely not in this case. curr -> ~Node(); Deletes data in sPtr, bur leaves memory for Node itself allocated.
You shouldn't even consider to do manual destructor call until you understand what "placement new" is, differences between new and operator new, and you run into situation where it is suitable to use that.
Best course of action:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
LinkedList:: ~LinkedList()
{
Node* curr = head;
Node* next = nullptr;
while (curr)
{
next = curr -> getNext();
delete curr;
curr = next;
}
head = NULL;
tail = NULL;
}
And line 9...."delete curr".....don't I also need to delete sPtr, and also set sPtr to NULL, and set curr -> next to NULL along with curr -> prev to NULL?
(Maybe it's worth mentioning that sPtr is a pointer to a student object and essentially contains the data in each node)