You are here:

C++/Global Objects Creation Priority

Advertisement


Question
Hi Ralph,

I have two objects defined in global namespace:
ICString glb_ProgBuildDate(SOME_AUTOCONF_MACRO);
ICLogFile glb_Log(stderr);

the problem here is ICString, whose code uses glb_Log for printing profiling and debugging info, so I would like to know, is there some way to initialize glb_Log first, or may be it is better way to define all global data as pointers, and initialize all such objects in main()?

I'm on gcc 4.0.1 / linux

Any help appreciated.

Answer
OK. There is _no_ way to order the initialisation of global objects (i.e. non-local static objects). There are _no_ guarantees what so ever on what order non-local static objects are created. The order can differ between build tools, different versions of the same build tools, different installations of the same tools and even from one build to the next as the project progresses. I have first hand experience of this problem and can confirm how fragile any code that relies on a specific ordering of non-local static object initialisation can be. This is particularly true of non-local static objects defined in different compilation units. You can expect that a compiler may initialise non-local static objects within one translation unit (i.e. source file) in some predictable fashion, most obviously in the order they are defined. When the objects are in different translation units things become more complex in fact so complex it is halting problem difficult.

On the other hand there are guarantees on when static local objects are constructed: when the function and code block they are in is first executed. This leads us to a work around. Move each global object into its own function, defined as static. Each function returns a reference to the object:

ICString & glb_ProgBuildDate()
{
   static ICString progBuildDate(SOME_AUTOCONF_MACRO);
   return progBuildDate;
}

ICLogFile & glb_Log()
{
   static ICLogFile log(stderr);
   return log;
}

Now everywhere you use glb_ProgBuildDate you replace it with glb_ProgBuildDate() and each use of glb_Log becomes glb_Log(). Of course if you feel you should modify the names further then do so, maybe to something like theProgBuildDate() and theLog(). This technique is sometimes called the Singleton Pattern and works so long as there is a reasonable initialisation order. If progBuildDate must be initialised before log and log must be initialised before progBuildDate then nothing is going to help and you should take a long hard look at your design!

For a fuller exposition on this subject see Scott Meyers book "Effective C++" I think it is up to the 3rd edition. In my second edition copy the item you want is "Item 47: Ensure that non-local static objects are initialised before they're used".

Note that the above idiom helps with the order of static object initialisation but does nothing for the order of static object destruction. If you have dependencies here then you need a more complex approach. For one such approach, see Andrei Alexandrescu's book "Modern C++ Design Generic Programming and Design Patterns Applied", in particular chapter 6 "Implementing Singletons", although you will probably find reading at least some of the initial chapters of use in understanding where Andrei is coming from.

On a final note: remember the old advice that global data is a bad thing, so try to keep it to a minimum.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.