Destructor Question

May 5, 2013 at 7:41pm
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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
LinkedList:: ~LinkedList()
{
        Node * curr = head;

        while (curr -> getNext())
        {
                curr = curr -> getNext();
                curr -> getPrev() -> ~Node();
        }
        curr -> ~Node();

        if (head -> getNext() || head -> get_sPtr() || head -> getPrev())
                cout << "Destructor failed to deallocate memory properly\n";

        head = NULL;
        tail = NULL;

/*      Node Class destructor

        if(sPtr)
                delete sPtr;
        next = NULL;
        prev = NULL;
        sPtr = NULL;
*/

}



Does this release all the dynamically allocated memory as well as all other necessary cleanup? I really wouldn't know how to check...
Last edited on May 5, 2013 at 8:00pm
May 5, 2013 at 9:01pm
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;
}
Last edited on May 5, 2013 at 9:04pm
May 5, 2013 at 9:13pm
Thanks a lot! Good to know!!!

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)

Or are those things not really necessary?
Last edited on May 5, 2013 at 9:19pm
May 5, 2013 at 9:18pm
delete first calls destructor, then frees memory. Two in one! And also it guaranteed to work on null pointers. So your node destructor can just be:
1
2
3
4
~Node()
{
    delete sPtr;
}
(You don't need to set pointers to null actually)
Topic archived. No new replies allowed.