Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!ncar!unmvax!polyslo!ttwang From: ttwang@polyslo.CalPoly.EDU (Thomas Wang) Newsgroups: comp.lang.c++ Subject: Re: Global Variable Constructors, Language design Message-ID: <14243@polyslo.CalPoly.EDU> Date: 7 Sep 89 20:38:40 GMT References: <6487@columbia.edu> Reply-To: ttwang@polyslo.CalPoly.EDU (Thomas Wang) Distribution: usa Organization: Cal Poly State University -- San Luis Obispo Lines: 45 kearns@cs.columbia.edu writes: >In C++, classes often do some initialization before the program >starts. It has been pointed out often in this newsgroup that C++ >suffers because one cannot predict the order in which the various files >will be initialized. However, one of the most serious ramifications >just hit me: >If a class, say class List, needs to do some initialization, then it >is UNSAFE to declare any global variable of type List, or any global >variable containing a List. The global may be initialized before the >List class is, probably causing serious problems. This is not quite it, but you came close. Eg. a::a() { cout << "initing...\n"; } static a an_object; Now you are in trouble; 'cout' might be initialized after 'an_object' is initialized. >Yech. Anybody have any other suggestions? The solution is really complicated. Say that you have a class caled 'type_car'. Basically you want to get a list of global variables and static variables one could ever use during type_car's construction phase. Remove from the list those variables that do not have constructors. A global variable of 'type_car' must be created after all those variables left in the list are created. The same operation goes for destructors too. You want to get a list of global variables and static variables one could ever use during type_car's destruction phase. Remove from the list those variables that do not have destructors. A global variable of 'type_car' must be destroyed after all those variables in the list are destroyed. >-steve -Thomas Wang ("I am, therefore I am." - Akira ) ttwang@polyslo.calpoly.edu