c++stdc++26

When should I use a std::inplace_vector instead of a std::vector?


There is a new std::inplace_vector in the C++ standard library that seems to have a fixed capacity defined at compile time. I'm trying to understand a use case for std::inplace_vector instead of std::array or std::vector. It seems like std::inplace_vector has the advantage of a fixed size capacity, like std::array, but instead does not require object initialization until insertion. But, unlike std::vector, std::inplace_vector has a fixed compile-time capacity.

Can anyone provide an example of where std::inplace_vector might be useful?


Solution

  • std::array requires the element type to be default constructible if you default construct the array

    std::inplace_vector on the other hand does not since default construction creates no objects in the vector

    This also means you can use a loop to initialize the members of the inplace_vector where you can't with a std::array.


    Also, pointed out by @Quimby

    inplace_vector<T,N> can store up to N elements while array<T,N> always stores N elements. For the latter one had to track the number of active elements separately. So the same reasoning for prefering std::span over pointer+length tuples can apply.