title: C++ struct alignment and STL vectors
body: <p>I have a legacy data structure that's 672 bytes long. These structs are stored in a file, sequentially, and I need to read them in.</p>
  
  <p>While I can read them in one-by-one, it would be nice to do this:</p>
  
  <pre><code>// I know in advance how many structs to read in
  vector&lt;MyStruct&gt; bunchOfStructs;
  bunchOfStructs.resize(numberOfStructs);
  
  ifstream ifs;
  ifs.open("file.dat");
  if (ifs) {
      ifs.read(&amp;bunchOfStructs[0], sizeof(MyStruct) * numberOfStructs);
  }
  </code></pre>
  
  <p>This works, but I think it only works because the data structure size happens to be evenly divisible by my compiler's struct alignment padding. I suspect it'll break on another compiler or platform.</p>
  
  <p>The alternative would be to use a <code>for</code> loop to read in each struct one-at-a-time.</p>
  
  <p>The question --> When do I have to be concerned about data alignment? Does dynamically allocated memory in a vector use padding or does STL guarantee that the elements are contiguous?</p>