title: How to use STL-compliant allocators for heterogeneous memory allocations
body: <p>I'm trying to implement a class that's followed in memory by an array of some arbitrary type:</p>
  
  <pre><code>template&lt;class T&gt;
  class Buf
  {
      size_t n;
      int refs;
      explicit Buf(size_t n) : n(n) { }
      // other declarations are here as appropriate
  
      // Followed in memory by:
      // T items[n];
  };
  </code></pre>
  
  <p>This would be easy with <code>operator new</code>:</p>
  
  <pre><code>template&lt;class T&gt;
  Buf&lt;T&gt; *make_buf(size_t n)
  {
      // Assume the caller will take care of constructing the array elements
      return new(operator new(sizeof(Buf&lt;T&gt;) + sizeof(T) * n)) Buf&lt;T&gt;(n);
  }
  
  template&lt;class T&gt;
  void free_buf(Buf&lt;T&gt; *p)
  {
      // Assume the caller has taken care of destroying the array elements
      p-&gt;~Buf&lt;T&gt;();
      return operator delete(p);
  }
  
  template&lt;class T&gt;
  T *get_buf_array(Buf&lt;T&gt; *p)
  {
      return reinterpret_cast&lt;T *&gt;(reinterpret_cast&lt;char *&gt;(p) + sizeof(Buf&lt;T&gt;));
  }
  </code></pre>
  
  <p>But now, how do I implement this using some standard-compliant <strong>allocator</strong> <code>SomeAllocator</code>?</p>
  
  <p>Is it guaranteed that <code>SomeAllocator::rebind&lt;char&gt;::other::allocate</code> will return memory suitably aligned for any type of object? If so, am I otherwise safe to just use an allocator of some char type? If not, do I have any alternatives, or is this task impossible with allocators in general? (In the worst case I suppose I could cast the pointers to <code>uintptr_t</code> and align them manually, but I'm wondering if there's a better way.)</p>