I have a private member
std::list<MyClass*> myclass_list;
which is part of OtherClass.
When i close my console application, the empty Destructor of OtherClass is called. The problem is, that during the destructor call – some methods within OtherClass want to iterate over myclass_list – e.g.
for(std::list<MyClass*>::iterator it = myclass_list.begin(); it != myclass_list.end(); ++it) {
// do stuff
}
Now, even tho the myclass_list is empty (and was never assigned/added a single variable to it during its lifetime) – the for loop will iterate at least once – basically accessing non-existing MyClass objects.
All this goes away when i switch from std::list to std::vector.
- What is the issue with the STL (VS2010) of list here? How can i check for an invalid list (!= 0 or !vector doesnt work there is no overloaded operator).
- I gather it works fine for vector because it uses continous memory and therefor the loop never gets executed.
EDIT: Ok i think the issue might be with accessing an invalid Otherclass object which is currently, the destructor is called. Otherclass is a global object.
Workflow ~OtherClass -> delete someMemberObject -> ~someMemberObject -> otherclass->CheckMyClassList(someMemberObject) -> crash
Destructors of member variables are called in the inverse order of declaration.
So, if the destructor of any member variable needs to access to other member variable, then the used variable should be declared before:
If the variables are defined in the opposite order, then when
~someMemberObject()is called, themyclass_listdestructor would have been called, and any use of it would result in undefined behavior.