title: Is there a way to increase the efficiency of shared_ptr by storing the reference count inside the controlled object?
body: <p>This is becoming a common pattern in my code, for when I need to manage an object that needs to be noncopyable because either A. it is "heavy" or B. it is an operating system resource, such as a critical section:</p>
  
  <pre><code>class Resource;
  
  class Implementation : public boost::noncopyable
  {
      friend class Resource;
      HANDLE someData;
      Implementation(HANDLE input) : someData(input) {};
      void SomeMethodThatActsOnHandle() {
          //Do stuff
      };
  public:
      ~Implementation() { FreeHandle(someData) };
  };
  
  class Resource
  {
      boost::shared_ptr&lt;Implementation&gt; impl;
  public:
      Resource(int argA) explicit {
          HANDLE handle = 
              SomeLegacyCApiThatMakesSomething(argA);
          if (handle == INVALID_HANDLE_VALUE)
              throw SomeTypeOfException();
          impl.reset(new Implementation(handle));
      };
      void SomeMethodThatActsOnTheResource() {
          impl-&gt;SomeMethodThatActsOnTheHandle();
      };
  };
  </code></pre>
  
  <p>This way, shared_ptr takes care of the reference counting headaches, allowing <code>Resource</code> to be copyable, even though the underlying handle should only be closed once all references to it are destroyed.</p>
  
  <p>However, it seems like we could save the overhead of allocating shared_ptr's reference counts and such separately if we could move that data inside <code>Implementation</code> somehow, like boost's intrusive containers do.</p>
  
  <p>If this is making the premature optimization hackles nag some people, I actually agree that I don't need this for my current project. But I'm curious if it is possible.</p>