title: STL Containers, SBO and custom allocator conflicts
body: <p>I've recently been fiddling with developing a custom allocator based on a memory pool, that is shared between multiple instances of the allocator.</p>
  
  <p>The intention was that the allocator be compatible with STL and Standard C++ based containers such as vector, deque, map, string etc</p>
  
  <p>However something in particular has caused me some confusion. Various implementations of the containers such as <strong>std::vector</strong>, <strong>std::string</strong> make use of Small Buffer Optimisation - stack based allocation for small initial memory requirements.</p>
  
  <p>For example MSVC9.1 has the following member in the basic_string class:</p>
  
  <pre><code>union _Bxty
  {   // storage for small buffer or pointer to larger one
     _Elem _Buf[_BUF_SIZE];
     _Elem *_Ptr;
     char _Alias[_BUF_SIZE];  // to permit aliasing
  } _Bx;
  </code></pre>
  
  <p>I can't see how when instantiating such containers one can cajole
  the implementation to only and always use the provided allocator
  and not use SBO. I ask because one of intentions of implementing
  custom allocators was to be able to use them in a shared memory
  context, where the amount of the shared memory may be less than
  the SBO limit some of the various implementations may use.</p>
  
  <p>For example I would like to have a situation where I can have two
  instances of std::string one per process sharing a common block
  of memory which maybe smaller than or equal to the SBO upper
  limit.</p>
  
  <p>Possibly related: <a href="https://stackoverflow.com/questions/8190950/may-stdvector-make-use-of-small-buffer-optimization">May std::vector make use of small buffer optimization?</a></p>
  
  <pre><code>typedef std::vector&lt;int,mysharedmemallocator&gt; shmvtype;
  
  shmvtype v(2,0); //&lt;-- if SBO then error as memory is allocated on
                   //stack not via the allocator
  
  v[1] = 1234;  //&lt;-- if SBO then error as wrong piece of memory
                // is being modified.
  </code></pre>
  
  <p>Lets look at another example that is not based on shared memory as it seems to over complicate things for some people. Lets say I want to specialize my std::basic_string or std::vector etc with an allocator that fills the memory it allocates with the value 0xAB prior to presenting the pointer back to the calling entity for no reason other than whimsy. </p>
  
  <p>A container that is specialised with this new allocator, but that also uses SBO, will not have its SBO based memory filled with 0xAB pattern. So for example:</p>
  
  <pre><code>typedef std::basic_string&lt;char,myfillmemallocator&gt; stype
  
  stype s;
  s.resize(2);
  
  assert(s[0] == 0xAB); // if SBO this will fail.
  </code></pre>