title: C++ Circular Dependency Explanation
body: <p>I have a basic example of a circular dependency using smart pointers.
  I've been looking for some explanations, and I know how to solve this problem, but I want to know what it is happening behind the scenes.</p>
  
  <p>This is the code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;memory&gt;
  using namespace std;
  
  class Child;
  class Parent {
    public:
      shared_ptr&lt;Child&gt; child;
      string name;
      Parent(string n) : name(n) {
        cout &lt;&lt; "Parent: " &lt;&lt; name &lt;&lt; " constructor" &lt;&lt; endl;
      }
      ~Parent() {
        cout &lt;&lt; "Parent: " &lt;&lt; name &lt;&lt; " destructor" &lt;&lt; endl;
      }
  };
  
  class Child {
    public:
      shared_ptr&lt;Parent&gt; parent;
      string name;
      Child(string n) : name(n) {
        cout &lt;&lt; "Child: " &lt;&lt; name &lt;&lt; " constructor" &lt;&lt; endl;
      }
      ~Child() {
        cout &lt;&lt; "Child: " &lt;&lt; name &lt;&lt; " destructor" &lt;&lt; endl;
      }
  };
  
  int main(int argc, char** argv) {
    shared_ptr&lt;Parent&gt; parent = make_shared&lt;Parent&gt;("Dad");//parent.use_count() =&gt; 1
    shared_ptr&lt;Child&gt; child = make_shared&lt;Child&gt;("Child");//child.use_count() =&gt; 1
    parent-&gt;child = child;//child.use_count() =&gt; 2
    child-&gt;parent = parent;//parent.use_count() =&gt; 2
    return 0;
  }
  //what happend at the end of the program?
  //what happend when the shared_ptr destructors were called?
  //was parent.use_count() decremented or is still 2?
  //was child.use_count() decremented or is still 2?
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>Parent: Dad constructor
  Child: Child constructor
  </code></pre>
  
  <p>What I want to know is the following</p>
  
  <ul>
  <li>what happen when the shared_ptr destructors are called?</li>
  <li>is parent.use_count() decremented or is still 2?</li>
  <li>is child.use_count() decremented or is still 2?</li>
  </ul>
  
  <p>I suppose the shared_ptr destructor code is something like:</p>
  
  <pre><code>~shared_ptr() {
    //I want to know what it is happening right here
    if (canDeletePointer(pointer)) {
      delete pointer;
    }
  }
  </code></pre>
  
  <p>Thanks</p>