title: G++ gets order of destruction of static variables wrong
body: <p>I have the following classes that try to implement a generic Singleton.</p>
  
  <pre><code>struct BaseObject
  {
     virtual ~BaseObject() {}
  };
  class _helper
  {
  private:
      template&lt;typename T&gt; friend class Singleton;
      set&lt;BaseObject*&gt; _s;
      static _helper&amp; _get()
      {
          static _helper t;
          return t;
      }
      _helper()
      {
          cout&lt;&lt;" _helper ctor"&lt;&lt;endl;
      }
      ~_helper()
      {
          cout&lt;&lt;" _helper dtor"&lt;&lt;endl;
          //assert(_s.empty());
      }
  };
  
  // Singleton&lt;foo&gt;::Instance() returns a unique instance of foo
  template &lt;typename T&gt;
  class Singleton : virtual private T
  {
  public:
      static T&amp; Instance()
      {
          static Singleton&lt;T&gt; _T;
          return _T;
      } 
  
  private:
      Singleton()
      {
          cout&lt;&lt;"inserting into helper "&lt;&lt;typeid(T).name()&lt;&lt;" ptr "&lt;&lt;this&lt;&lt;endl;
          assert(!_helper::_get()._s.count(this));
          _helper::_get()._s.insert(this);
      }
      ~Singleton()
      {
          cout&lt;&lt;"erasing from helper "&lt;&lt;typeid(T).name()&lt;&lt;" ptr "&lt;&lt;this&lt;&lt;endl;
          assert(_helper::_get()._s.count(this));
          _helper::_get()._s.erase(this);
      }
  };
  </code></pre>
  
  <p>Now if I call <code>Singleton&lt; bar&gt;::Instance()</code> followed by <code>Singleton&lt; foo&gt;::Instance()</code>, I should see the following output:</p>
  
  <pre><code> inserting into helper 3bar ptr 0x509630  
   _helper ctor  
   inserting into helper 3foo ptr 0x509588  
   erasing from helper 3foo ptr 0x509588  
   erasing from helper 3bar ptr 0x509630  
   _helper dtor  
  </code></pre>
  
  <p>However in some cases, I see the following:</p>
  
  <pre><code> inserting into helper 3bar ptr 0x509630  
   _helper ctor  
   inserting into helper 3foo ptr 0x509588  
   erasing from helper 3bar ptr 0x509630  
   _helper dtor  
   erasing from helper 3foo ptr 0x509588  
  </code></pre>
  
  <p>Note that in the second case, <code>bar</code> and <code>foo</code> got destructed in the same order as they were constructed. This seems to happen when the <code>foo</code> and <code>bar</code> singletons are instantiated inside a shared library(.so) as static references:</p>
  
  <pre><code>static bar&amp; b = Singleton&lt;bar&gt;::Instance();   
  static foo&amp; f = Singleton&lt;foo&gt;::Instance();   
  </code></pre>
  
  <p>Any ideas why it would do that?</p>