title: C++ static initialization order
body: <p>When I use static variables in C++, I often end up wanting to initialize one variable passing another to its constructor. In other words, I want to create static instances that depend on each other. </p>
  
  <p>Within a single .cpp or .h file this is not a problem: the instances will be created in the order they are declared. However, when you want to initialize a static instance with an instance in another compilation unit, the order seems impossible to specify. The result is that, depending on the weather, it can happen that the instance that depends on another is constructed, and only afterwards the other instance is constructed. The result is that the first instance is initialized incorrectly.</p>
  
  <p>Does anyone know how to ensure that static objects are created in the correct order? I have searched a long time for a solution, trying all of them (including the Schwarz Counter solution), but I begin to doubt there is one that really works.</p>
  
  <p>One possibility is the trick with the static function member:</p>
  
  <pre><code>Type&amp; globalObject()
  {
      static Type theOneAndOnlyInstance;
      return theOneAndOnlyInstance;
  }
  </code></pre>
  
  <p>Indeed, this does work. Regrettably, you have to write globalObject().MemberFunction(), instead of globalObject.MemberFunction(), resulting in somewhat confusing and inelegant client code.</p>
  
  <p><b>Update:</b> Thank you for your reactions. Regrettably, it indeed seems like I have answered my own question. I guess I'll have to learn to live with it...</p>