title: C++ Function output changes after return
body: <p>I am trying to get a vector of trees from a DFS traversal of a graph but the result changes after it is returned from the function.</p>
  
  <p>This is the Tree class:</p>
  
  <pre><code>template &lt;typename T&gt;
  class Tree
  {
  public:
      T v;    // value of current node
      // List of subtrees
      std::list&lt;Tree&lt;T&gt;*&gt; children;
      // Pointer to parent
      Tree&lt;T&gt; *parent;
      Tree(T v) {
          this-&gt;v = v;
      }
  }
  </code></pre>
  
  <p>This is the relevant part of the function </p>
  
  <pre><code>    for (int i = 0; i &lt; V; ++i)
          trees.push_back(Tree&lt;T&gt;(info[i]));
  
      int parent, node;
      std::vector&lt;int&gt; roots;
      for (int i = 0; i &lt; V; ++i) {
          parent = parents[i];
          node = path[i];
  
          if (parent != -1) {
              trees[parent].children.push_back(&amp;trees[node]);
              trees[node].parent = &amp;trees[parent];
          }
          else {
              roots.push_back(node);
          }
      }
      for(int node_i : roots)
          res.push_back(trees[node]);
      return res;
  </code></pre>
  
  <p>and the variable declarations are these:</p>
  
  <pre><code>        template &lt;typename T&gt;
      std::vector&lt;Tree&lt;T&gt;&gt; DFSTree(std::vector&lt;T&gt; &amp;info) {
      std::vector&lt;Tree&lt;T&gt;&gt; res;
      std::vector&lt;int&gt; path;
      std::vector&lt;int&gt; parents;
      std::vector&lt;Tree&lt;T&gt;&gt; trees;
  </code></pre>
  
  <p>The Tree within the resulting vectors' children don't have any children set.
  Sorry if this is a basic question but I couldn't find an answer anywhere.
  Thank you for the response</p>