LinkedList::~LinkedList()
{
NodePointer ptr = first;
while (first->next)
{
first = ptr->next;
delete ptr;
ptr = first;
}
if (first == 0) cout << "List destroyed\n";
else cout << "List not destroyed\n";
}
This is what I had before I started experimenting, and it does not work
yea i saw.
comment this in your main out
cout << "\nHere's another list:\n" << anotherList << endl;
something in this calls the destructor again.
ostream & operator<<(ostream & out, const LinkedList list);
Well well, it ran successfully with that line commented out... :/ I'm not passing the list by reference, so shouldn't it make a copy of it for use in the function? if so, why does it fail
yeah i dont know the workins of cout << >> and all that C++ garbage.
but id does change the reference of the list. if you debug it you can see that the address of anotherlist changes after that cout.
Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
Consider what happens. If no appropriate copy constructor is supplied, the runtime will supply one for you. Your linked list contains a pointer to a type. When you call the insertion operator (makes a copy) it will use the default method. This method simply copies the VALUE of the pointer (eg: the memory address that holds your list). It will not, however, allocate the memory for the list and copy it. (See: deep copy vs. shallow copy). When the insertion operator returns to the caller, the destructor deletes the memory that the pointer points to (your linked list is now gone). When the actual linked list goes out of scope, the destructor is called again on memory that has been freed.
That error is MSVC's debug free heuristic that is telling you that the memory has already been flagged to be returned to the handler.
Consider what happens. If no appropriate copy constructor is supplied, the runtime will supply one for you. Your linked list contains a pointer to a type. When you call the insertion operator (makes a copy) it will use the default method. This method simply copies the VALUE of the pointer (eg: the memory address that holds your list). It will not, however, allocate the memory for the list and copy it. (See: deep copy vs. shallow copy). When the insertion operator returns to the caller, the destructor deletes the memory that the pointer points to (your linked list is now gone). When the actual linked list goes out of scope, the destructor is called again on memory that has been freed.
That error is MSVC's debug free heuristic that is telling you that the memory has already been flagged to be returned to the handler.
Gotter love bad worksheets eh? I'll try adding the copy constructor a bit later