1 2 3
|
int main(){
List list;
}
|
Crash.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
List::~List()
{
//size is 0, next is NULL
node *current=start, *next=start->next;
int j=size; //this just obfuscate things
for(int i=0;i<=j;i++)
{
delete current;
current=next; //current is NULL
if(current->next!=0) //dereferencing NULL pointer
{
next=current->next;
}
}
}
|
If you do want to use the empty header cell,
1 2 3 4 5
|
class List{
node start; //an object, not a pointer
};
List::List(): start(NULL, NULL, 42)//initialization list to construct your members
{
|
You may notice that you can't use
place() to emulate an
append. Try to solve that.
A destructor is used to release resources when they would not be needed anymore. By instance, closing a file.
Or to inform others that you are dead (because they may care).
In C++ the destructors are called automagically when the object goes out of scope. Its destructor will also call at the destructors of its members.
In your case you are requesting memory to create the nodes. That memory needs to be freed when you end using it (when the list dies). Because the destuctor of a pointer will not
delete
the pointer, you need to code that logic.
The list has the ownership of the nodes and it is responsible of free them.
However your nodes only hold dynamic references. They do not "own" their neighbours.
Still, you may want to tell to your neighbour "I'm dying, your reference is invalid", so they adjust it.
Keep in mind the rule of three.
If you need a destructor, a copy constructor or an assignment operator, you need the three.
Edit: as node is an inner class you need to qualify the name
List::Node::~Node(){