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;
}
}
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::destroy is recursive, which is quite inefficient. You would need perhaps to replace it with iterative approach:
void sorted_list::destroy(list_link* item)
{
while (item)
{
list_link* old = item;
item = item->next;
delete old;
}
}
(And you should take into account @Roger Pate's comment and not delete this->first the second time after calling destroy(this->first);.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With