0

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.

  1. 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).
  2. 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

Steve
  • 738
  • 1
  • 9
  • 30

1 Answers1

1

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:

class OtherClass
{
    std::list<MyClass*> myclass_list;
    someMemberObject member;
};

If the variables are defined in the opposite order, then when ~someMemberObject() is called, the myclass_list destructor would have been called, and any use of it would result in undefined behavior.

rodrigo
  • 94,151
  • 12
  • 143
  • 190
  • I see, thanks - is there still any way to check if a stl::list container is valid before doing any operation (e.g. size) on it? – Steve Jul 03 '12 at 00:04
  • 1
    @Steve: No, sorry, once the object's destructor has been invoked _any_ operation on it is undefined by definition. So there is no general method to achieve what you ask. Anyway, it looks like you are trying to fight the object system of C++... These rules are there for some very good reasons, and you would do better if you play along and take advantage of the rules instead of trying to play around them. – rodrigo Jul 03 '12 at 00:45
  • yes i know, thanks - but with a failsave (e.g. some kind of null check for containers) my application would only report an error, and not crash and i could fix it afterwards – Steve Jul 04 '12 at 22:44