title: shared_ptr and the this-pointer
body: <p>OK, I started using shared-pointers and pass shared-pointers as much as possible.  No conversion to raw pointers anymore.  This works good, except in this specific case:</p>
  
  <p>Suppose we have a class that also is an observer on another class, like this:</p>
  
  <pre><code>class MyClass : public IObserver
     {
     public:
        MyClass (std::shared_ptr&lt;SomeOtherClass&gt; otherClass);
        void DoSomethingImportant();
     private:
        std::shared_ptr&lt;SomeOtherClass&gt; m_otherClass;
     };
  </code></pre>
  
  <p>This class is used like this in my application:</p>
  
  <pre><code>std::shared_ptr&lt;MyClass&gt; myInstance(new MyClass(otherInstance));
  ...
  myInstance-&gt;DoSomethingImportant();
  </code></pre>
  
  <p>MyClass gets a shared-pointer to another class and stores this in its m_otherClass data member.
  In the DoSomethingImportant method, the MyClass instance does lots of important things, including registering itself as an observer on m_otherClass, like this:</p>
  
  <p>m_otherClass->registerObserver(this);</p>
  
  <p>The problem is that the registerObserver method is defined like this:</p>
  
  <p>void registerObserver (std::shared_ptr observer);</p>
  
  <p>It expects a shared pointer, but 'this' is a raw pointer, not a shared one.</p>
  
  <p>I see three ways of solving this:</p>
  
  <ul>
  <li>Find a trick to convert a normal pointer to a shared pointer (see question <a href="https://stackoverflow.com/questions/887524/convert-pointer-to-shared-ptr">convert pointer to shared_ptr</a>), but the answers to that question only suggest to copy the shared-pointers, not on how to actually convert the pointer to a shared pointer.</li>
  <li>Pass the shared-pointer to ourself to the method, like this: "myInstance->DoSomethingImportant(myInstance);" which seems a bit stupid.</li>
  <li>Put the observer part into a separate class.  This looks like some overkill, and might make the class harder to understand.</li>
  </ul>
  
  <p>This problem makes it obvious that shared-pointers are just an add-on to C++ (I don't think you have the same problem in other languages/environments like C# (or .Net in general) and Java).</p>
  
  <p>Any other suggestions or tricks on how to handle this situation?</p>