title: solution to a std::vector of std::shared_ptr leaking due to circular reference
body: <p>I've gotten myself into a pickle: I'm coding a tree graph structure, where each layer contains a vector of pointers to previous layers (super types) and pointers to following (sub types) layers.</p>
  <p>As you can imagine, this is a circular reference:</p>
  <pre><code>[last] -(super)-&gt; [current]
  [current] -(sub)-&gt; [last]
  </code></pre>
  <p>When I allocate a new <code>layer</code> I make sure I move it to <code>current</code>
  and when I re-assign last to current, again I move it.</p>
  <p>However, this doesn't solve the leak, in fact the only solution I've found is using raw pointers.</p>
  <p>Here's a minified example omitting large parts of the code:</p>
  <pre><code>struct layer
  {
      std::unordered_set&lt;std::string&gt; words;
      std::vector&lt;layer*&gt; sub_classes;
      std::vector&lt;layer*&gt; super_classes;
  }
  </code></pre>
  <p>The actual iteration is of <code>wordnet senses</code> which populate a tree graph.
  The function that does the <code>hypernyms</code> (e.g., super-types of a word) is:</p>
  <pre><code>void iterate_sense(
                          Synset * sense,
                          std::shared_ptr&lt;layer&gt; last,
                          graph &amp; rhs,
                          int lexical
                        )
      {
          std::shared_ptr&lt;layer&gt; current;
          while (sense &amp;&amp; last)
          {
              current = std::move(get_layer(sense));
              last-&gt;super_classes.push_back(current.get());
              current-&gt;sub_classes.push_back(last.get());
              if (sense-&gt;ptrlist)
              {
                  iterate_sense(sense-&gt;nextss, 
                                last,
                                rhs, lexical);
              }
              last = std::move(current);
              sense = sense-&gt;ptrlist;
          }
      }
  </code></pre>
  <p>Those pointers are owned by another class <code>graph</code>.
  When I use in <code>layer</code></p>
  <pre><code>    std::vector&lt;std::shared_ptr&lt;layer&gt;&gt; sub_classes;
      std::vector&lt;std::shared_ptr&lt;layer&gt;&gt; super_classes;
  </code></pre>
  <p>Valgrind reports lost bytes.</p>
  <h2>1</h2>
  <p>What is the <em>correct</em> or <em>elegant</em> way of solving this?
  I assume that using raw pointers is not the best solution?</p>
  <h2>2</h2>
  <p>Am I correct to assume that the moment the owner <code>graph</code> is lost,
  the raw pointers will become invalid?
  This isn't much of a problem because <code>layers</code> themselves reside only in graphs.</p>
  <h2>3</h2>
  <p>I've read around SO and google that the correct usage is via combination of <code>std::weak_ptr</code> and <code>std::shared_ptr</code> however I don't understand how a weak_ptr would be used in such a case.</p>