title: Nifty/Schwarz counter, standard compliant?
body: <p>I had a discussion this morning with a colleague about static variable initialization order.  He mentioned the <a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Nifty_Counter" rel="noreferrer">Nifty/Schwarz counter</a> and I'm (sort of) puzzled.  I understand how it works, but I'm not sure if this is, technically speaking, standard compliant.</p>
  
  <p>Suppose the 3 following files (the first two are copy-pasta'd from <a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Nifty_Counter" rel="noreferrer">More C++ Idioms</a>):</p>
  
  <hr>
  
  <pre><code>//Stream.hpp
  class StreamInitializer;
  
  class Stream {
     friend class StreamInitializer;
   public:
     Stream () {
     // Constructor must be called before use.
     }
  };
  static class StreamInitializer {
    public:
      StreamInitializer ();
      ~StreamInitializer ();
  } initializer; //Note object here in the header.
  </code></pre>
  
  <hr>
  
  <pre><code>//Stream.cpp
  static int nifty_counter = 0; 
  // The counter is initialized at load-time i.e.,
  // before any of the static objects are initialized.
  StreamInitializer::StreamInitializer ()
  {
    if (0 == nifty_counter++)
    {
      // Initialize Stream object's static members.
    }
  }
  StreamInitializer::~StreamInitializer ()
  {
    if (0 == --nifty_counter)
    {
      // Clean-up.
    }
  }
  </code></pre>
  
  <hr>
  
  <pre><code>// Program.cpp
  #include "Stream.hpp" // initializer increments "nifty_counter" from 0 to 1.
  
  // Rest of code...
  int main ( int, char ** ) { ... }
  </code></pre>
  
  <hr>
  
  <p>... and here lies the problem!  There are two static variables:</p>
  
  <ol>
  <li>"nifty_counter" in <code>Stream.cpp</code>; and</li>
  <li>"initializer" in <code>Program.cpp</code>.</li>
  </ol>
  
  <p>Since the two variables happen to be in two different compilation units, there is no (AFAIK) <em>official</em> guarantee that <code>nifty_counter</code> is initialized to 0 before <code>initializer</code>'s constructor is called.</p>
  
  <p>I can think of two quick solutions as two why this "works":</p>
  
  <ol>
  <li>modern compilers are smart enough to resolve the dependency between the two variables and place the code in the appropriate order in the executable file (highly unlikely);</li>
  <li><code>nifty_counter</code> is actually initialized at "load-time" like the article says and its value is already placed in the "data segment" in the executable file, so it is always initialized "before any code is run" (highly likely).</li>
  </ol>
  
  <p>Both of these seem to me like they depend on some unofficial, yet possible implementation.  Is this standard compliant or is this just "so likely to work" that we shouldn't worry about it?</p>