Skip links

C++26: std::inplace_vector

C++26 has introduced a new collection data structure called inplace_vector. It is a variant of the existing std::vector that was originally introduced in C++98 with gradual improvements over the years.

So what is inplace_vector? As the name suggests, it is a fixed capacity, in-place contiguous array. As in the case of vector, we can use methods such as “insert”, “emplace_back”, “push_back”, etc. to add elements to the collection. Here is an example to get started:

Adding Elements
Adding Elements

We create the inplace_vector to store “string”, fixing its capacity as 4. This means we can add not more than 4 strings in this object. No dynamic space allocation takes place when we insert elements. Also keep in mind that the entire memory for holding the names object with all its elements is allocated on the stack. This is different from how vector operates.

Here is the output when we run the program:

Program Output
Program Output

While “capacity” is the upper limit on how many elements may be inserted in the object, “size” tells us how many actual elements live inside the object. In the above example, since we added only 3 elements, the size happens to be 3, whereas the capacity is pegged at 4.

What happens when we try to add more elements than the “capacity”? “std::bad_alloc” exception is thrown.

Trying to Exceed Capacity
Trying to Exceed Capacity

Here is the program output:

Program Output
Program Output

We can also use the “try_push_back” or “try_emplace_back” if we decide to explicitly handle the boundary case.

Using "try_emplace_back"
Using “try_push_back”

The corresponding output is:

The Output
The Output

I think it is useful to touch upon a subtle point here. When we have user-defined types as elements of the inplace_vector, there is no compulsion to have a “default” no-arg constructor in that type. That is because the container elements are not automatically default initialized. The following example shows this:

No Need for Default Ctor
No Need for Default Constructor

Here is the output:

Output from Program
Output from Program

In the above example, there is no default constructor for “X” class. This won’t work for std::array<X, N> objects!

I hope std::inplace_vector is clear now.

I tested the examples in Compiler Explorer using “x86-64 gcc 16.2” with the compiler option “-std=c++26”.

Have a great week!

Leave a comment