title: Dynamic TLS in C++11
body: <p>I'm writing a C++11 class Foo, and I want to give each instance its own thread-local storage of type Bar.  That is to say, I want one Bar to be allocated per thread <em>and</em> per Foo instance.</p>
  
  <p>If I were using pthreads, Foo would have a nonstatic member of type pthread_key_t, which Foo's constructor would initialize with pthread_key_create() and Foo's destructor would free with pthread_key_delete().  Or if I were writing for Microsoft Windows only, I could do something similar with TlsAlloc() and TlsFree().  Or if I were using Boost.Thread, Foo would have a nonstatic member of type boost::thread_specific_ptr.</p>
  
  <p>In reality, however, I am trying to write portable C++11.  C++11's <code>thread_local</code> keyword does not apply to nonstatic data members.  So it's fine if you want one Bar per thread, but not if you want one Bar per thread per Foo.</p>
  
  <p>So as far as I can tell, I need to define a thread-local map from Foos to Bars, and then deal with the question of how to clean up appropriately whenever a Foo is destroyed.  But before I undertake that, I'm posting here in the hope that someone will stop me and say "There's an easier way."</p>
  
  <p>(Btw, the reason I'm not using either pthread_key_create() or boost::thread_specific_ptr is because, if I understand correctly, they assume that all threads will be spawned using pthreads or Boost.Thread respectively.  I don't want to make any assumptions about how the users of my code will spawn threads.)</p>