FAQ 16.14 Is it safe to be ignorant of the static initialization order problem?

No, ignorance of the static initialization order problem can result in application crashes.

The static initialization order problem has to do with the lifetimes of class-scope static objects and file-scope or namespace-scope objects. These objects are constructed near the beginning of the application's execution (often before main() begins) and are destructed after main() finishes. The nightmare scenario occurs when there is an order dependency between initializations across different compilation units (that is, different .cpp files). This can be both dangerous and subtle.

For example, suppose a constructor of class Fred uses a static data member of class Wilma, and a user creates a global Fred object. If the static objects in the user's source file are initialized before those in the source file containing Fred's static data member, Fred's constructor will access a Wilma object before it is constructed.

Although this description sounds uncommon, it actually shows up quite often in practice, especially with factory objects whose constructor registers something in a "registry" object. For example, Wilma is actually a map (a registry object) and Fred is a "factory" object whose constructor registers something in the map.

In the following example, the order of the global Fred and the static data member have been arranged to simulate this disaster.

 #include <iostream> using namespace std; class Wilma { public:   Wilma()  throw();   void f() throw(); }; inline Wilma::Wilma()  throw() { cout << "Wilma ctor\n"; } inline void Wilma::f() throw() { cout << "Wilma used\n"; } class Fred { public:   Fred() throw(); protected:   static Wilma wilma_; }; inline Fred::Fred() throw() {   cout << "Fred ctor\n";   wilma_.f(); } Fred x; Wilma Fred::wilma_; int main() { } 

The (annotated) output from this program shows that the Wilma object is used before it is initialized. This is a disaster.

 Fred ctor Wilma used                                           <-- 1 Wilma ctor                                           <-- 2 

(1) The static object is used

(2) The static object is constructed



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net