Local buffer optimization beyond strings
The local buffer optimization can be used effectively for much more than just short strings. In fact, any time a small dynamic allocation of a size that is determined at runtime is needed, this optimization should be considered. In this section, we will consider several such data structures.
Small vector
Another very common data structure that often benefits from local buffer optimization is vectors. Vectors are essentially dynamic contiguous arrays of data elements of the specified type (in this sense, a string is a vector of bytes, although null termination gives strings their own specifics). A basic vector, such as std::vector
found in the C++ standard library, needs two data members, a data pointer and the data size:
// Example 06 class simple_vector { public: simple_vector() = default; simple_vector(std::initializer_list<int> il) : n_(il.size()), ...