title: Heap/dynamic vs. static memory allocation for C++ singleton class instance
body: <p>My specific question is that when implementing a <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="noreferrer">singleton class</a> in C++, is there any substantial differences between the two below codes regarding performance, side issues or something:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>class singleton
  {
      // ...
      static singleton&amp; getInstance()
      {
          // allocating on heap
          static singleton* pInstance = new singleton();
          return *pInstance;
      }
      // ...
  };
  </code></pre>
  
  <p>and this:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>class singleton
  {
      // ...
      static singleton&amp; getInstance()
      {
          // using static variable
          static singleton instance;
          return instance;
      }
      // ...
  };
  </code></pre>
  
  <p><br/>
  (Note that dereferencing in the heap-based implementation should not affect performance, as AFAIK there is no extra machine-code generated for dereferencing. It's seems only a matter of syntax to distinguish from pointers.)</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>I've got interesting answers and comments which I try to summarize them here. (Reading detailed answers is recommended for those interested.)‎:</p>
  
  <ul>
  <li>In the singleton using <em>static</em> local variable, the class destructor is automatically invoked at process termination, whereas in the <em>dynamic allocation</em> case, you have to manage object destruction someway at sometime, e.g. by using smart pointers:</li>
  </ul>
  
  <pre class="lang-cpp prettyprint-override"><code>    static singleton&amp; getInstance() {
          static std::auto_ptr&lt;singleton&gt; instance (new singleton());
          return *instance.get(); 
      }
  </code></pre>
  
  <ul>
  <li><p>The singleton using dynamic allocation is <em>"lazier"</em> than the static singleton variable, as in the later case, the required memory for the singleton object is (always?) reserved at process start-up (as part of the whole memory required for loading program) and only calling of the singleton constructor is deferred to <code>getInstance()</code> call-time. This may matter when <code>sizeof(singleton)</code> is large.</p></li>
  <li><p>Both are thread-safe in C++11. But with earlier versions of C++, it's implementation-specific.</p></li>
  <li><p>The dynamic allocation case uses one level of indirection to access the singleton object, whereas in the static singleton object case, direct address of the object is determined and hard-coded at compile-time.</p></li>
  </ul>
  
  <p><br/>
  <em>P.S.: I have corrected the terminology I'd used in the original posting according to the @TonyD's answer.</em></p>