问题
Here is my test code:
#include <iostream>
#include <cstdlib>
using namespace std;
class List
{
private:
class Node{
public:
int data;
Node* next;
public:
virtual ~Node()
{
if (next != NULL)
{
cout << "Node is out: " << data << endl;
delete next;
}
}
Node()
{
next = NULL;
}
};
Node* head;
public:
virtual ~List()
{
if (head != NULL)
{
delete head;
}
}
List()
{
head = NULL;
}
public:
void AddNode(int data);
void DeleteNode(int data);
//....
};
void List::AddNode(int data)
{
Node* temp = new Node;
temp -> data = data;
if (head == NULL)
{
head = temp;
}
else
{
Node* ptr = head;
while (ptr -> next != NULL)
{
ptr = ptr -> next;
}
ptr -> next = temp;
}
}
int main()
{
List test_list;
test_list.AddNode(1);
test_list.AddNode(2);
test_list.AddNode(3);
test_list.AddNode(4);
test_list.AddNode(5);
return 0;
}
The output is like this:
Node is out: 1
Node is out: 2
Node is out: 3
Node is out: 4
It a common list and you can pay attention to the two destructor function for Node and List. I thought this one can work but the out showed that the last node cannot be deleted. I also test for other number of nodes. The result is the same, last node cannot be deleted. Thanks ahead for your advices:-).
回答1:
Change your destructor to print on the outside of the if
statement.
The destructor is being called, however, on your last node next
is NULL
, so the if
statement returns false
and the cout line is not being called.
virtual ~Node()
{
cout << "Node is out: " << data << endl;
if (next != NULL)
{
delete next;
}
}
来源:https://stackoverflow.com/questions/22998753/destructor-of-list-cannot-delete-the-last-node