title: Thread safe singleton implementation in C++
body: <p>The following is a well known implementation of singleton pattern in C++.<br>
  However, I'm not entirely sure whether its thread-safe.<br>
  Based upon answers to similar question asked here previously, it seems it is thread safe.<br>
  Is that so?  </p>
  
  <pre><code>//Curiously Recurring Template Pattern    
  //Separates a class from its Singleton-ness (almost).    
  #include &lt;iostream&gt;  
  using namespace std;
  
  template&lt;class T&gt; class Singleton {
    Singleton(const Singleton&amp;);
    Singleton&amp; operator=(const Singleton&amp;);
  protected:
    Singleton() {}
    virtual ~Singleton() {}
  public:
    static T&amp; instance() {
      static T theInstance;
      return theInstance;
    }
  };
  
  // A sample class to be made into a Singleton
  class MyClass : public Singleton&lt;MyClass&gt; {
   int x;
  protected:
    friend class Singleton&lt;MyClass&gt;;
    MyClass() { x = 0; }
  public:
   void setValue(int n) { x = n; }
    int getValue() const { return x; }
  };
  </code></pre>