title: Pointers into elements in a container
body: <p>Say I have an object:</p>
  
  <pre><code>struct Foo 
  {
      int bar_;
      Foo(int bar) bar_(bar) {}
  };
  </code></pre>
  
  <p>and I have an STL container that contains <code>Foo</code>s, perhaps a vector, and I take </p>
  
  <pre><code>// Elsewhere...
  
  vector&lt;Foo&gt; vec;
  
  vec.push_back(Foo(4));
  
  int *p = &amp;(vec[0].bar_)
  </code></pre>
  
  <p>This is a terrible idea, right? </p>
  
  <p>The reason is that <code>vector</code> is going to be storing its elements in a dynamically allocated array somewhere, and eventually, if you add enough elements, it will have to allocate another array, copy over all the elements of the original array, and delete the old array. After that happens, <code>p</code> points to garbage. This is why many operations on a <code>vector</code> will invalidate iterators.</p>
  
  <p>It seems like it would be reasonable to assume that an operation that would invalidate iterators from a container will also invalidate pointers to data members of container elements, and that if an operation <em>doesn't</em> invalidate iterators, those pointers will still be safe. However, many reasonable assumptions are false. Is this one of them?</p>