title: Struct hack equivalent in C++
body: <p>The struct hack where you have an array of length 0 as the last member of a struct from C90 and C99 is well known, and with the introduction of flexible array members in C99, we even got a standardized way of using it with <code>[]</code>. Unfortunately, C++ provides no such construct, and (at least with Clang <strong>3.4</strong>), compiling a struct with either <code>[0]</code> or <code>[]</code> will yield a compilation warning with <code>--std=c++11 -pedantic</code>:</p>
  
  <pre><code>$ cat test.cpp 
  struct hack {
    char filler;
    int things[0];
  };
  $ clang++ --std=c++11 -pedantic test.cpp
  \test.cpp:3:14: warning: zero size arrays are an extension [-Wzero-length-array]
    int things[0];
  </code></pre>
  
  <p>and similarly</p>
  
  <pre><code>$ cat test.cpp 
  struct fam {
    char filler;
    int things[];
  };
  $ clang++ --std=c++11 -pedantic test.cpp
  \test.cpp:3:7: warning: flexible array members are a C99 feature [-Wc99-extensions]
    int things[];
  </code></pre>
  
  <p>My question then is this; say that I want to have a struct that contains an array of variable size as the last item in C++. What is the right thing to do given a compiler that supports both? Should I go with the struct hack <code>[0]</code> (which is a compiler extension), or the FAM <code>[]</code> (which is a C99 feature)? As far as I understand it, either will work, but I am trying to figure out which is the lesser evil?</p>
  
  <p>Also, before people start suggesting keeping an <code>int*</code> to a separately allocated piece of memory in the struct instead, that is not a satisfactory answer. I want to allocate a single piece of memory to hold both my struct and the array elements. Using a std::vector also falls into the same category. If you wonder why I don't want to use a pointer instead, the <a href="https://stackoverflow.com/questions/18001710/are-flexible-array-members-really-necessary/18001919#18001919">R.'s answer</a> to another question gives a good overview.</p>
  
  <p>There have been some similar questions elsewhere, but none give an answer to this particular question:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/4412749/are-flexible-array-members-valid-in-c">Are flexible array members valid in C++?</a>: Very similar, but the question there is whether FAM is valid in C++ (no). I am looking for a good reason to pick one or the other.</li>
  <li><a href="https://stackoverflow.com/questions/18310789/conforming-variant-of-the-old-struct-hack">Conforming variant of the old “struct hack”</a>: Proposes an alternative, but it's neither pretty, nor always correct (what if padding is added to the struct?). Accessing the elements later is also not as clean as doing <code>e.things[42]</code>.</li>
  </ul>