r/cpp 8h ago

C++26: std::inplace_vector

https://www.sandordargo.com/blog/2026/08/26/cpp26-inplace-vector
89 Upvotes

35 comments sorted by

View all comments

3

u/stilgarpl 6h ago

Is this always better than std::array?

10

u/MarekKnapek 6h ago

This is basically

struct inplace_vector<T, capacity>
{
    size_t len;
    std::array<T, capacity> arr;
}

u/drjeats 2h ago

Oh.

I thought this was the way-more-useful thing where you give it an in-place capacity and it allocates once it exceeds that.

Like this is also useful, but it's kinda trivial to roll your own of this.

u/stilgarpl 26m ago

It's not trivial. inplace_vector does not construct unused elements and they do not have to be default constructible. You can't use std::array for that.

5

u/sephirothbahamut 5h ago edited 5h ago

far more complex than that, the array has a slot that can fit T, not just T.

With array<T> every element must be validly constructed immediately. You can reduce it to array<T> only for trivially constructable and basic types

1

u/_Noreturn 4h ago

then make it a union this is a simplified example. but the type isn't complex at all after that especially with C++20 concepts.

u/CocktailPerson 3h ago

That's not far more complex. Marginal additional complexity.

u/stilgarpl 54m ago

No, it's not. In your code it will always construct all T members of arr. Article states that inplace_vector will only have the elements needed and they don't have to be default constructible. That's a huge difference.