Search code examples
c++boostc++11

Using vector<char> as a buffer without initializing it on resize()


I want to use vector<char> as a buffer. The interface is perfect for my needs, but there's a performance penalty when resizing it beyond its current size, since the memory is initialized. I don't need the initialization, since the data will be overwritten in any case by some third-party C functions. Is there a way or a specific allocator to avoid the initialization step? Note that I do want to use resize(), not other tricks like reserve() and capacity(), because I need size() to always represent the significative size of my "buffer" at any moment, while capacity() might be greater than its size after a resize(), so, again, I cannot rely on capacity() as a significative information for my application. Furthemore, the (new) size of the vector is never known in advance, so I cannot use std::array. If vector cannot be configured that way, I'd like to know what kind of container or allocator I could use instead of vector<char, std::alloc>. The only requirement is that the alternative to vector must at most be based on STL or Boost. I have access to C++11.


Solution

  • There's nothing in the standard library that meets your requirements, and nothing I know of in boost either.

    There are three reasonable options I can think of:

    • Stick with std::vector for now, leave a comment in the code and come back to it if this ever causes a bottleneck in your application.
    • Use a custom allocator with empty construct/destroy methods - and hope your optimiser will be smart enough to remove any calls to them.
    • Create a wrapper around a a dynamically allocated array, implementing only the minimal functionality that you require.