Path: utzoo!mnetor!uunet!husc6!cmcl2!nrl-cmf!ames!ucbcad!pasteur!ucbvax!ulysses!hector!jss From: jss@hector.UUCP (Jerry Schwarz) Newsgroups: comp.lang.c++ Subject: Re: Ordering of initialisation of static classes in *different* files ? Message-ID: <3345@ulysses.homer.nj.att.com> Date: 18 Jan 88 19:43:49 GMT References: <734@hslrswi.UUCP> Sender: daemon@ulysses.homer.nj.att.com Reply-To: jss@hector (Jerry Schwarz) Organization: AT&T Bell Labs, Murray Hill Lines: 60 Keywords: static class initialisation ordering In article <734@hslrswi.UUCP> robert@hslrswi.UUCP (J. Robert Ward) writes: > >It seems to me that there is a (small) defect in the definition of >the C++ language. Namely, the order in which static objects are >initialised is apparently undefined when more than one source file >is under consideration. > The technique I use is to avoid statically intialized objects of types with constructors in favor of a the following. In the header, myclass.h, that declares the objects I want initialized I do. static class Myclass_init { static int count ; public: Myclass_init() ; ~Myclass_init() ; } myclass_init ; In myclass.c I put the definitions: Myclass_init::Myclass_init() { if ( count++ > 0 ) return ; // Allocate and initialize whatever needs to be // initialized here } Myclass_init::~Myclass_init() { if ( --count > 0 ) return ; // Free (and destroy) whatever needs to be // freed here. } This means that typically I declare pointers to objects rather than the objects themselves. The constructor and destructor is called once for every time the header is included. The manipulations of "count" arrange that the initialization and freeing is done only once. Because the order of calls to static initializers within a file is guaranteed, and the declaration of myclass_init occurs higher in the file than any use of the objects declared in myclass.h, the initialzation occurs before any use and the freeing after any use. > >Question: how can I guarantee that cout is properly initialised >by its constructor before it gets passed as an argument to the >constructor foo::foo() ? Since both cout and foo1 are global >objects, I presume the order of construction is undefined. >Or am I missing something here ? > With regard to I/O, I wrote a replacement for streams that uses the above technique to initialize cin, cout and cerr. It will probably be included in the next release of cfront. Jerry Schwarz