title: C++11: Nontrivial Thread Local Static Variable?
body: <p>I have a class X:</p>
  
  <pre><code>class X { ... }
  </code></pre>
  
  <p>I want to do this:</p>
  
  <pre><code>void f()
  {
      thread_local static X x = ...;
  
      ...
  }
  </code></pre>
  
  <p>(actually I'm using gcc so keyword is "__thread")</p>
  
  <p>but I can't because you can only have trivial thread_locals.</p>
  
  <p>What is the best work-around for this?</p>
  
  <p>If I do it this way:</p>
  
  <pre><code>void f()
  {
      thread_local static X* p = 0;
  
      if (!p)
         p = new X(...);
  
      X&amp; x = *p;
  
      ...
  }
  </code></pre>
  
  <p>then:</p>
  
  <ol>
  <li>the destructor won't be called when thread exits</li>
  <li>unnecessary dynamic memory allocation.</li>
  </ol>
  
  <p><strong>Update:</strong></p>
  
  <p>Here is what I have so far:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;type_traits&gt;
  
  using namespace std;
  
  class X { public: X() { cout &lt;&lt; "X::X()" &lt;&lt; endl; }; ~X() { cout &lt;&lt; "X::~X()" &lt;&lt; endl; } };
  
  void f()
  {
          static __thread bool x_allocated = false;
          static __thread aligned_storage&lt;sizeof(X),
               alignment_of&lt;X&gt;::value&gt;::type x_storage;
  
          if (!x_allocated)
          {
                  new (&amp;x_storage) X;
                  x_allocated = true;
                  // add thread cleanup that calls destructor
          }
  
          X&amp; x = *((X*) &amp;x_storage);
  }
  
  int main()
  {
          f();
  }
  </code></pre>
  
  <p>This fixes the dynamic memory allocation problem.  I just need to add the thread cleanup handler.  Is there a mechanism to do this with pthreads?</p>