To clear up one misconception, the destructor is called any time an object goes out of scope (a local variable hits the end of the code block in which it was created). If an object was created in global scope (outside of a function) it will be destroyed at program exit. Think of this as a big set of braces around the whole program.
void function(object a)
{
object b;
int x = 0;
while (x < 10)
{
object c;
// La la la Doing stuff.
} // c destroyed here. It will be created and destroyed for each run through the loop
a = b;
} //b destroyed here
// a also destroyed here, so watch out passing things into functions if you want them
// back changed.
or when it is manually destroyed with the delete
command
object * d = new object();
// la la la doing stuff
delete d;
Since d
was manually created, it must be manually destroyed. Watch out C# and Java people.
What do you need to do in a destructor?
Put everything away. Don't waste your time setting values back to their defaults. They won't be around long enough to appreciate the gesture. But if you opened a file, and still have it open, close it. If you new
ed other objects, delete
them. If you have a mutex locked, unlock it. If you are managing threads, you probably want to notify the threads and wait for them to finish before finishing. But do it with a time-out so you don't hang on a stuck thread.
While we're on the topic, read this: What is The Rule of Three?
Put simply The Rule of Three means if you have a destructor, a copy constructor or an assignment operator (operator=
), you almost certainly require all three. A lot of time you'll see people getting odd memory errors because they didn't obey the Rule of Three. Don't be that guy.
When you have The Rule of Three down, go looking for the Rule of Five.
How this applies to the OP:
List::~List
{
head = NULL; //very probably need to delete this pointer
tail = NULL; //and possibly this one
count = 1; // don't need this at all
}
So it should probably look like:
List::~List
{
if (head != NULL)
{
delete head; // This should start a chain reaction deleting all of the linked
// items in the list, ensuring that they have all been freed
}
}
In addition, the OP should have a copy constructor and an assignment operator that make sure that when the List is deleted it doesn't also obliterate the data of any copies of the list.