Hey I wonder about
I have written a C++ linked list, where I call a destructor to go through an allocated linked list and delete every node found. However what I found is that although it goes through the linked list and delete every occurance it will still print out values. Although just some scrap values.
But shouldn’t it be when I delete the linked_list it shouldn’t be printable next time?
I’m create a linked list by using the new, and delete when I remove the list
sorted_list::~sorted_list()
{
// Destructor implementation
destroy(this->first);
cout << "Destructor called sorted_list" << endl;
}
void sorted_list::destroy(list_link* item)
{
if (item)
{
destroy(item->next);
delete item;
}
}
print function
void sorted_list::print() {
if(this->first)
{
iteratorn *traverse = new iteratorn(this->first);
while( !traverse->iterator_end() )
{
cout << traverse->iterator_get_key() << " ";
traverse->iterator_next();
}
delete traverse;
}
else
cout << "list empty" << endl;
}
When you access a destructed object, the behaviour is undefined. In fact, deleting an object doesn’t clear the memory, just marks it available, so if you execute some operations on already deleted object, they may do something reasonable. But again, the object is destructed, so you must not access it.
Of course, you should not retain any pointers to the object belonging to the linked list after it’s destructed, because those objects will be destructed as well.
By the way, your
sorted_list::destroyis recursive, which is quite inefficient. You would need perhaps to replace it with iterative approach:(And you should take into account @Roger Pate’s comment and not delete
this->firstthe second time after callingdestroy(this->first);.)