title: Calling std::vector::push_back() is changing previous elements in vector?
body: <p>First off, some boiled down code:</p>
  
  <pre><code>#ifndef UNDIRECTED_GRAPH_HPP
  #define UNDIRECTED_GRAPH_HPP
  
  #include &lt;vector&gt;
  #include &lt;iostream&gt;
  
  template &lt;typename T&gt;
  struct undirected_graph
  {
      struct node
      {
          T data;
      };
  
      struct edge
      {
          node&amp; node0;
          node&amp; node1;
      };
  
      ~undirected_graph() {
          for (auto n : nodes_) delete n;
          for (auto e : edges_) delete e;
      }
  
      const node&amp; add_new_node(const T&amp; data);
  
  private:
      std::vector&lt;node*&gt; nodes_;
      std::vector&lt;edge*&gt; edges_;
  };
  
  template &lt;typename T&gt;
  const typename undirected_graph&lt;T&gt;::node&amp;
  undirected_graph&lt;T&gt;::add_new_node(const T&amp; data)
  {
      node *n = new node { data };
      nodes_.push_back(n);
      for (auto x : nodes_) std::cout &lt;&lt; x-&gt;data.pos.x &lt;&lt; "," &lt;&lt; x-&gt;data.pos.y &lt;&lt; std::endl;
      return *n;
  }
  
  #endif
  </code></pre>
  
  <p>The problem exists in <code>undirected_graph::add_new_node(const T&amp; data)</code>. I added the output to console for debugging purposes, since I'm only using this class with my own data type so far. Everytime I'm calling this method, it seems the previous entries in the<code>nodes_</code> vector are all being changed to the last element.</p>
  
  <p>I figured it might have to do with the type of data I'm choosing to store in my graph, so I'm adding the part of the code that calls it as well:</p>
  
  <pre><code>// Somewhere in dungeon_generator.cpp ...
  undirected_graph&lt;const DungeonLayout::Room&amp;&gt; graph;
  
  for (auto room : dungeon-&gt;rooms) {
      graph.add_new_node(room);
  }
  </code></pre>
  
  <p>So either my method is flawed, or the way I'm calling it is flawed, or both. But I can't seem to figure out what is going wrong! Can someone please help me?</p>
  
  <p>To illustrate the problem even further, I've added the output of a couple of calls to the method. The <code>dungeons_-&gt;rooms</code> container contains a bunch of rooms at randomly generated positions (denoted by their <code>pos</code> attribute)</p>
  
  <pre><code>2,2
  9,9
  9,9
  3,2
  3,2
  3,2
  2,6
  2,6
  2,6
  2,6
  9,3
  9,3
  9,3
  9,3
  9,3
  </code></pre>