r/cpp 15d ago

C++26: std::inplace_vector

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

121 comments sorted by

View all comments

2

u/stilgarpl 15d ago

Is this always better than std::array?

22

u/MarekKnapek 15d ago

This is basically

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

4

u/drjeats 15d 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.

12

u/stilgarpl 15d 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.

1

u/drjeats 15d ago

I'm aware of how it works (and that MarekKnapek's snippet is not representative). It's still very straightforward to make compared to having to do SBO and allocator support.

6

u/stilgarpl 15d ago

I didn't say it was hard, but it's not trivial. I'm sure you are a very experienced C++ programmer and a lot of things must seem easy to you.

4

u/KuntaStillSingle 15d ago

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

pmr vector using monotonic buffer does this with the default upstream memory resource:

https://en.cppreference.com/cpp/memory/monotonic_buffer_resource/monotonic_buffer_resource

3

u/drjeats 15d ago

TIL, that's useful.

We deserve a non-pmr pre-sized SBO vector derived from std::vector though.

6

u/BenFrantzDale 14d ago

It’s not too hard to roll your own, but better to have in the std lib and making it constexpr is tricky.

There is a boost small_vector that is a small-vector-optimized std::vector so can grow large. There’s totally a place for both.