title: C++ Vector Push_back producing Weird Side Effect
body: <p>While I was using STL vector to store class objects,, I observed a very weird side effect, where push_back method modifies the Existing Data!</p>
  
  <p>Basically I have a class containing several fields as follows:</p>
  
  <pre><code>class MyClass {
      MyClass(std::string s, int i) {
          StringValue = s;
          IntValue = i;
      }
  
      std::string StringValue;
      int IntValue;
  }
  </code></pre>
  
  <p>I have a vector that contains the <strong>POINTERS</strong> to MyClass objects.. and then I am basically pushing back references to objects:</p>
  
  <pre><code>std::vector&lt;MyClass*&gt; MyVector;
  MyClass c1("CLASS 1", 1);
  MyClass c2("CLASS 2", 2);
  
  MyVector.push_back(&amp;c1);
  // Result:
  // *MyVector[0]    ==&gt;    ("Class 1", 1)
  
  
  
  MyVector.push_back(&amp;c2);
  // Result:
  // *MyVector[0]    ==&gt;    ("Class 2", 2)   ??why 2??
  // *MyVector[1]    ==&gt;    ("Class 2", 2)
  </code></pre>
  
  <p>Do you see the strange result that I got??  I've set breakpoints after each push_back statement,,, and this weird thing happened.</p>
  
  <p>The first push_back statement worked fine. But then the second push_back statement <strong>MODIFIED</strong> the content of the first element, which doesn't make sense to me.. </p>
  
  <p>I'm assuming that it has something to do with me storing References instead of actual objects inside the vector.... but I can't figure out what is wrong.</p>
  
  <p>How can I handle this issue? Any insights?</p>
  
  <p>Thanks</p>
  
  <p><br>
  <strong>UPDATE:</strong></p>
  
  <p>(simplified code)</p>
  
  <pre><code>MyClass c1("CLASS 1", 1);
  MyClass c2("CLASS 2", 2);
  
  MyClass temp;
  while (int i=0; i&lt;2; i++) {
      temp = c1;
      MyVector.push_back(temp);
  }
  </code></pre>
  
  <p>You guys are right,, I get what I'm doing wrong here.. The actual object gets destructed in every loop..   What's the best way to fix this while keeping the current structure??  I'ts hard to explain but I would like to keep this structure (keeping temporary buffer outside the loop).. is this possible?</p>