Reputation: 111
I am working on an assignment that requires me to reimplement all of the Linked List functions. I am having some trouble understanding what the deconstructor does or what the code would be for it. I wrote a code that would deconstruct the list, but I don't think that is right (found below). I am also under the impression that I need to call the deconstructor in many of the LinkedList functions. Can someone please explain this to me and give me an idea of what the deconstructor code would look like?
~list()
{
for(int i=0; i<length; i++)
{
pop_front();
}
delete head;
}
Upvotes: 0
Views: 3315
Reputation: 70030
Unless your code is visible, the exact solution cannot be suggested. You need to deallocate all the dynamically allocated linked list node if you are using your hand-written linked list. You can also use std::list
.
The "destructor" should not be called explicitly, however it will be called as part of delete
call. One way to destruct the 0 ending link list is as (example pseudo code):
class node {
int data;
node *next;
public:
~node()
{
delete this->next; // this will be chained until NULL is found
}
};
class list {
node *head;
...
public:
~list()
{
delete head;
}
};
And then call,
Upvotes: 2
Reputation: 73473
You have a memory leak as you are not doing delete
of all the list nodes. A typical implementation could be like this:
For each node in the list
delete node;
Clear the entire list;
Also,
I am also under the impression that I need to call the deconstructor in many of the LinkedList functions
No, you should not call the destructor explicitly from any of your functions. It is called automatically when either the object goes out of scope or when somebody does a delete
of you list. This entirely depends on the code which is using your list
class. However, note that you may want to delete a single node from the list in functions such as erase
, but that doesn't mean that you have to call the destructor of list.
Upvotes: 1