title: How to use automatic reference counting and virtual functions together in the C++?
body: <p>I had been searching the answer for this problem for a long.</p>
  
  <p>I want to use shared data (shared_ptr or something similar) where it's possible and where it's necessary of course. But I also want to use virtual functions. As you can see below, there is a contradiction in the usage of them together.</p>
  
  <p>I protect the data of class in this manner:</p>
  
  <pre><code>class MyObject {
  public:
      void method() {
          // no memory leak here, because this contains
          // count of references of Data inside shared_ptr
          OtherObject::otherMethod(this);
      }
  private:
      class Data {};
      shared_ptr&lt;Data&gt; data;
  };
  </code></pre>
  
  <p>Because if I simply nest my class MyObject inside the shared_ptr, I will not be able to pass "this" raw pointer safely outside of the MyObject class in some method. Raw pointer is not protected with reference counting.</p>
  
  <p>Example:</p>
  
  <pre><code>class MyObject {
  public:
      void method() {
          // memory leak here, because this does not contain
          // count of references of Data or of self (MyObject) 
          OtherObject::otherMethod(this);
      }
  private:
      class Data {};
      Data data;
  };
  
  ...
  
  shared_ptr&lt;MyObject&gt; crazyLeakingObject;
  </code></pre>
  
  <p>crazyLeakingObject leaks, because it has MyObject inside with all its data and methods, but it is only MyObject without any information about count of the references. In the MyObject's methods we have no such information.</p>
  
  <p>The first approach I use when I do not need virtual functions. But the second is for the virtual functions. As you know, you can access vtable only through pointer (raw pointer) of the existing object. But raw pointers and protected shared pointers are opposites.
  Usage of this two approaches together makes the architecture of my projects messy.
  And there is a leaks in the second approach.</p>
  
  <p>Is there a way to use virtual functions and automatic reference counting? Where I can find an examples? Did you faced with the problem?</p>
  
  <p>I am not a native English speaker, so you may ask for the clarifications.</p>
  
  <p>Thanks in advance.</p>