title: Best way to protect from multiple shared_ptr to the same object
body: <p>Sending the same pointer into two different <code>shared_ptr</code>'s is bad, it causes double deallocation, like thus:</p>
  
  <pre><code>int* p = new int;
  std::shared_ptr&lt;int&gt; p1(p);
  std::shared_ptr&lt;int&gt; p2(p); // BAD
  </code></pre>
  
  <p>You can accomplish the same purpose with <code>std::enable_shared_from_this</code>:</p>
  
  <pre><code>class Good: public std::enable_shared_from_this&lt;Good&gt;
  {
  public:
      std::shared_ptr&lt;Good&gt; getptr() {
          return shared_from_this();
      }
  };
  
  int main()
  {
      std::shared_ptr&lt;Good&gt; gp1(new Good);
      std::shared_ptr&lt;Good&gt; gp2 = gp1-&gt;getptr();
  }
  </code></pre>
  
  <p>But that still doesn't protect against:</p>
  
  <pre><code>class Good: public std::enable_shared_from_this&lt;Good&gt;
  {
  public:
      std::shared_ptr&lt;Good&gt; getptr() {
          return shared_from_this();
      }
  };
  
  int main()
  {
      Good* p = new Good;
      std::shared_ptr&lt;Good&gt; gp3(p);
      std::shared_ptr&lt;Good&gt; gp4(p); // BAD
  }
  </code></pre>
  
  <p>which could become a problem if you have code like this:</p>
  
  <pre><code>void Function(std::shared_ptr&lt;Good&gt; p)
  {
      std::cout &lt;&lt; p.use_count() &lt;&lt; '\n';
  }
  
  int main()
  {
      Good* p = new Good;
      std::shared_ptr&lt;Good&gt; p1(p);
      Function(p);    // BAD
  }
  </code></pre>
  
  <p>Why would I use a regular pointer when there's smart pointers? Because in performance critical code (or for convenience) the overhead of shared_ptr or weak_ptr is undesirable.</p>
  
  <p>To prevent this mistake, I've done:</p>
  
  <pre><code>class CResource : public shared_ptr&lt;Good&gt;
  {
  public:
      CResource()
      {
      }
  
      CResource(std::shared_ptr&lt;CBaseControl&gt; c)
          : CResource(c)
      {
      }
  
  private:
      CResource(CBaseControl* p)
      {
      }
  };
  
  void Function(CResource p)
  {
      std::cout &lt;&lt; p.use_count() &lt;&lt; '\n';
  }
  
  int main()
  {
      Good* p = new Good;
      CResource p1(std::shared_ptr&lt;Good&gt;(p));
      Function(p);    // Error
  }
  </code></pre>
  
  <p>This would cause the compiler to error if anyone tries to call <code>Function</code> with a pointer instead of a <code>shared_ptr</code>. It doesn't prevent someone from declaring <code>void Function(std::shared_ptr p)</code> though, but I think that's unlikely.</p>
  
  <p>Is this still bad? Is there a better way of doing this?</p>