title: why boost::scoped_ptr is cleared in a singleton implementation
body: <p>I implemented a simple singleton by using boost::scoped_ptr:</p>
  
  <pre><code>template &lt;class T&gt; class Singleton : public boost::noncopyable {
     public:
         static T&amp; instance() {
             boost::call_once(init, flag);
             return *t;
         }
         static void init() {
             t.reset(new T());
         }
      private:
         static boost::scoped_ptr &lt;T&gt; t;
        static boost::once_flag flag;
   };
   template &lt;class T&gt; boost::scoped_ptr&lt;T&gt; Singleton&lt;T&gt;::t(0);
   template &lt;class T&gt; boost::once_flag Singleton&lt;T&gt;::flag = BOOST_ONCE_INIT;
  </code></pre>
  
  <p>Define a real singleton class:</p>
  
  <pre><code> class S : public Singleton&lt;S&gt; {
       public:
          void p() { printf("hello");}
   };
  </code></pre>
  
  <p>Then I define a static variable in file S.cpp:</p>
  
  <pre><code>static volatile S &amp;S_instance = S::instance();
  </code></pre>
  
  <p>in main.cpp:</p>
  
  <pre><code> int main()
   {
        S &amp;ss = S::instance();
        ss.p();
   }
  </code></pre>
  
  <p>Run this program, an exception happened:</p>
  
  <blockquote>
    <p>/usr/include/boost/smart_ptr/scoped_ptr.hpp:91: T&amp; boost::scoped_ptr::operator*() const [with T = S]: Assertion `px != 0' failed  </p>
  </blockquote>
  
  <p>Tracing the code, I found the static s_instance.t is cleared once the code leaves the static initialization segment and after that all code referring to the S::instance will get NULL scoped_ptr. Does anybody know the reason?</p>
  
  <p><strong>[UPDATE]</strong>
  I tried to put all static into one cpp file (S1.cpp):</p>
  
  <pre><code>template &lt;class T&gt; boost::scoped_ptr&lt;T&gt; Singleton&lt;T&gt;::t(0);
  template &lt;class T&gt; boost::once_flag Singleton&lt;T&gt;::flag = BOOST_ONCE_INIT;
  
  static S&amp; s_ins = S::instance();
  </code></pre>
  
  <p>and debug it with GDB, it looks follow the order I wrote. any idea?</p>