问题
I have a linked_list and currently my destructor is not working properly. Not entirely sure why. Can somebody explain me how to solve this?
class linked_list {
private:
struct node
{
// String in this node
std::string data;
// Pointer to next node
struct node *next;
};
//First item in the list
struct node *first;
Here is my destructor
linked_list::~linked_list(void)
{
while (first)
{
delete first;
first = first->next;
}
}
回答1:
The problem lies here:
delete first;
first = first->next;
When you delete first
, but then try to access first->next
. Cache first->next
into a temp variable of type node*
, then do delete first
to fix this:
struct node* temp;
while (first != NULL)
{
temp = first->next;
delete first;
first = temp;
}
回答2:
change to
linked_list::~linked_list(void)
{
struct node *next;
while (first != NULL)
{
next = first->next;
delete first;
first = next;
}
}
来源:https://stackoverflow.com/questions/15672812/destructor-for-a-linked-list