title: Thread safe singleton in C++
body: <p>I have been reading about thread safe singletons and the implementation I find everywhere has a getInstance() method something like this:</p>
  
  <pre><code>Singleton* getInstance()
  {
      if ( !initialized )
      {
          lock();
          if ( !initialized )
          {
              instance = new Singleton();
              initialized = true;
          }
          unlock();
      }
  
      return instance;
  }
  </code></pre>
  
  <ul>
  <li>Is this actually thread safe?</li>
  <li>Have I missed something or is there a small chance this function will return an uninitialized instance because 'initialized' may be reordered and set before instance?</li>
  </ul>
  
  <p>This article is on a slightly different topic but the top answer describes why I think the above code is not thread safe:</p>
  
  <p><a href="https://stackoverflow.com/questions/2484980/why-is-volatile-not-considered-useful-in-multithreaded-c-or-c-programming">Why is volatile not considered useful in multithreaded C or C++ programming?</a></p>