Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!uunet!taumet!steve From: steve@taumet.com (Stephen Clamage) Newsgroups: comp.lang.c++ Subject: Re: Initializing Global Objects Message-ID: <750@taumet.com> Date: 27 May 91 15:41:25 GMT References: <76813@brunix.UUCP> <1991May27.060310.16757@mathcs.sjsu.edu> Organization: Taumetric Corporation, San Diego Lines: 47 horstman@mathcs.sjsu.edu (Cay Horstmann) writes: >In article <76813@brunix.UUCP> sdm@cs.brown.edu (Scott Meyers) writes: >> class nifty_counter { >> static count; >> public: >> nifty_counter() >> { >> if (count++ == 0) >> // initialize global objects (i.e., X) >> } >> }; > int nifty_counter::count = 0; >>Prior to this statement is the declaration of the static nifty_counter >>object, so we know that the nifty_counter constructor will have been called >>by the time that nifty_counter::count is explicitly initialized... >I think you have the wrong conception of the initialization of static >integers. They are just set to 0 in the load image, so it is guaranteed >that they are zero before any constructors of static objects are executed. Cay's analysis reflects current implementations, but not anything in the language definition. The language definition makes no distinction between the initialization of int i = 1; // value can be part of load image and extern int j, k; class C { C(int, int); ... }; C c(j, k); // value cannot be part of load image The requirement is merely that both initializations be complete before the first statement of main() is executed. In an embedded system, for example, non-const variables cannot be initialized in the "load image" (ROM) because they then could not be changed. All variables must be initialized at program startup, including nifty_counter::count. Thus, Scott's concern is not fanciful. The ANSI C++ committee (X3J16) is addressing the issue of static initialization, and in particular, how, if at all, initialization order can be specified. -- Steve Clamage, TauMetric Corp, steve@taumet.com