Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!think.com!spool.mu.edu!uunet!brunix!sdm From: sdm@cs.brown.edu (Scott Meyers) Newsgroups: comp.lang.c++ Subject: Initializing Global Objects Message-ID: <76813@brunix.UUCP> Date: 27 May 91 02:38:31 GMT Article-I.D.: brunix.76813 Sender: news@brunix.UUCP Reply-To: sdm@cs.brown.edu (Scott Meyers) Organization: Brown University Department of Computer Science Lines: 56 Section 3.4 of the ARM (pp. 20-21 of the American version) describes the standard method for ensuring that a global object X is initialized before it is used: put a static object inside each translation unit that can use X, and have the constructor for the static object's class initialize X. This is the function of the object iostream_init in the AT&T iostream library -- it is used to properly initialize the predefined streams cin, cout, etc. My question concerns the static class variable that is used to determine whether X has already been initialized. From the ARM: class nifty_counter { static count; public: nifty_counter() { if (count++ == 0) // initialize global objects (i.e., X) } }; We know that nifty_counter::count is preinitialized to 0 because it is static, but the rules of the language also require that it be initialized by the programmer somewhere. My question is this: to what value should it be initialized? In the iostream library, the value used is 0, i.e., one of the translation units contains the statement: 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. As a result, at the time when nifty_counter::count is initialized, it's value will no longer be 0, since it will have been incremented inside the constructor. If its value is reset to 0 (the explicit initialization value), then if a different nifty_counter object is subsequently initialized (possible, since it could be from a different translation unit), won't X be initialized *again*? In other words, shouldn't the proper initialization value of count be as follows? int nifty_counter::count = nifty_counter::count; I suspect I'm overlooking something here, because the folks working on the iostream library have had a lot of time to get it right. What am I missing? Thanks, Scott ------------------------------------------------------------------------------- What do you say to a convicted felon in Providence? "Hello, Mr. Mayor."