Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

std

c++26

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?

like image 814
The Mad Gamer Avatar asked Sep 09 '25 18:09

The Mad Gamer


2 Answers

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.

like image 143
NathanOliver Avatar answered Sep 13 '25 10:09

NathanOliver


std::inplace_vector provides a resizable container, that avoids memory allocations entirely.

This type is useful as a fast local container, as long as:

  • you know what the upper limit of its size will be
  • you don't need an O(1) complexity move operation
    • (The elements can be moved individually, but the container itself cannot be moved)
like image 41
Drew Dormann Avatar answered Sep 13 '25 09:09

Drew Dormann