/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */

folly/small_vector.h

folly/small_vector.h

folly::small_vector<T,Int=1,...> is a sequence container that implements small buffer optimization. It behaves similarly to std::vector, except until a certain number of elements are reserved it does not use the heap.

Like standard vector, it is guaranteed to use contiguous memory. (So, after it spills to the heap all the elements live in the heap buffer.)

Simple usage example:

    small_vector<int,2> vec;
    vec.push_back(0); // Stored in-place on stack
    vec.push_back(1); // Still on the stack
    vec.push_back(2); // Switches to heap buffer.

Details


This class is useful in either of following cases:

The last two cases were the main motivation for implementing it.

There are also a couple of flags you can pass into this class template to customize its behavior. You can provide them in any order after the in-place count. They are all in the namespace small_vector_policy.

A couple more examples:

    // With space for 32 in situ unique pointers, and only using a
    // 4-byte size_type.
    small_vector<std::unique_ptr<int>, 32, uint32_t> v;

    // A inline vector of up to 256 ints which will not use the heap.
    small_vector<int, 256, NoHeap> v;

    // Same as the above, but making the size_type smaller too.
    small_vector<int, 256, NoHeap, uint16_t> v;