Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!think.com!zaphod.mps.ohio-state.edu!swrinde!cs.utexas.edu!uwm.edu!lll-winken!sun-barr!apple!netcomsv!sjsumcs!horstman From: horstman@mathcs.sjsu.edu (Cay Horstmann) Newsgroups: comp.lang.c++ Subject: Re: Initializing Global Objects Message-ID: <1991May27.060310.16757@mathcs.sjsu.edu> Date: 27 May 91 06:03:10 GMT References: <76813@brunix.UUCP> Organization: San Jose State University - Math/CS Dept. Lines: 44 In article <76813@brunix.UUCP> sdm@cs.brown.edu (Scott Meyers) writes: > >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? To zero: int nifty_counter::count = 0; (The =0 is optional.) > >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*? > 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. (That is why in C this stuff was never an issue--all initial values of statics were precomputed by the loader.) There is no code explicitly setting nifty_counter::count to 0. Cay