title: c++ adding objects to vector destroys earlier objects
body: <p>I need to add objects of the same class to a vector:</p>
  
  <pre><code>#include &lt;vector&gt;
  #include &lt;cstdio&gt;
  
  class A {
      int *array;
      int size;
  public:
      A(int s) { 
         array = new int[size = s];
         fprintf(stderr, "Allocated %p\n", (void*)array);
      }
     ~A()      { 
         fprintf(stderr, "Deleting %p\n", (void*)array);
         delete array; 
      }
  };
  
  int main() {
      std::vector&lt;A&gt; v;
  
      for (int n = 0; n &lt; 10; n++) {
          fprintf(stderr, "Adding object %d\n", n);
          v.push_back(A(10 * n));
          //v.emplace_back(10 * n);
      }
      return 0;
  }   
  </code></pre>
  
  <p>When I run this program, it crashes after producing the following output:</p>
  
  <pre><code>Adding object 0
  Allocated 0x146f010
  Deleting 0x146f010
  Adding object 1
  Allocated 0x146f050
  Deleting 0x146f010
  *** glibc detected *** ./a.out: double free or corruption (fasttop): 0x000000000146f010 ***
  </code></pre>
  
  <p>It seems that the destructor of the 0th object is called when adding the 1st object.  Even stranger is when I use emplace_back instead of push_back:</p>
  
  <pre><code>Adding object 0
  Allocated 0x1644030
  Adding object 1
  Allocated 0x1644080
  Deleting 0x1644030
  Adding object 2
  Allocated 0x1644100
  Deleting 0x1644030
  Deleting 0x1644080
  Adding object 3
  Allocated 0x1644160
  Adding object 4
  Allocated 0x1644270
  Deleting 0x1644030
  *** glibc detected *** ./a.out: double free or corruption (fasttop): 0x0000000001644030 ***
  </code></pre>
  
  <p>Can someone explain why this is happening, and the correct way to do this?  Compiler used was g++ 4.7.2 under Linux, but I'm also getting the same behavior with clang 7.3.0 under Mac OS X.</p>