title: enable_shared_from_this: Sharing the use count in member
body: <p>Say I have two classes: <code>Thing</code> and <code>Holder</code>:</p>
  
  <pre><code>struct Thing :
          std::enable_shared_from_this&lt;Thing&gt;
  {
      std::shared_ptr&lt;Thing&gt; self()
      {
          return shared_from_this();
      }
  };
  
  struct Holder :
          std::enable_shared_from_this&lt;Holder&gt;
  {
      Thing t;
  };
  
  int main()
  {
      auto h = std::make_shared&lt;Holder&gt;();
      // will throw std::bad_weak_ptr
      h-&gt;t.self();
  }
  </code></pre>
  
  <p>I would like <code>Thing</code>'s internal <code>weak_ptr</code> to use the shared count for <code>Holder</code>, instead of <em>requiring</em> <code>Holder</code> to keep a <code>shared_ptr</code> to <code>Thing</code>. In the opposite direction, <code>Thing</code> needs to be able to exist without knowing what a <code>Holder</code> is (<code>std::make_shared&lt;Thing&gt;().self()</code> should still work). Is there a decent way to accomplish what I am looking for?</p>
  
  <hr>
  
  <h3>Things that Don't Work</h3>
  
  <p>Saying something like <code>std::shared_ptr&lt;Thing&gt; t(h, &amp;h-&gt;t);</code> does not work, since the aliasing constructor for a <code>std::shared_ptr</code> does not use the <code>enable_shared_from_this</code> visitor.</p>
  
  <p>With Boost, one could hack around this by overloading <code>sp_enable_shared_from_this</code>; however, with g++'s implementation, it isn't obvious how to do the equivalent with <code>__enable_shared_from_this_helper</code> (not to mention we're jumping into "DON'T DO THAT" land).</p>
  
  <hr>
  
  <h3>Boost Workarounds</h3>
  
  <p>When in Boost, it isn't terribly difficult to work around this issue by calling <code>_internal_accept_owner</code> directly:</p>
  
  <pre><code>int main()
  {
      auto h = boost::make_shared&lt;Holder&gt;();
      h-&gt;t._internal_accept_owner(&amp;h, &amp;h-&gt;t);
      h-&gt;t.self();
  }
  </code></pre>
  
  <p>With <code>boost::enable_shared_from_this2</code>, one can embed the needed code in the constructor of <code>Holder</code> like so:</p>
  
  <pre><code>Holder()
  {
      boost::shared_ptr&lt;Holder&gt; self = shared_from_this();
      t._internal_accept_owner(&amp;self, &amp;t);
  }
  </code></pre>
  
  <p>I'm looking to do the equivalent with <code>std::enable_shared_from_this</code>.</p>