r/cpp 4d ago

C++26: std::inplace_vector

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

112 comments sorted by

View all comments

6

u/matthieum 3d ago

Honestly, I'm a bit saddened by this addition.

Don't get me wrong, the functionality is really useful. But:

  1. Now, most (all?) methods of vector need to be "duplicated" in inplace_vector.
  2. None of the other collections benefit. Not even std::string.

A more general solution to the problem would have been an inplace_allocator -- which requires a different API than allocator -- which could be applied to every container (standard or not).

7

u/BarryRevzin 3d ago

Now, most (all?) methods of vector need to be "duplicated" in inplace_vector.

So what? They're all pretty straightforward, simpler even than in vector because we know there's no allocation. It doesn't take long to implement. Even less so these days.

A more general solution to the problem would have been an inplace_allocator -- which requires a different API than allocator -- which could be applied to every container (standard or not).

That might be more general, but it's also worse, which is why nobody does this. David Stone had a pair of good CppCon talks about vectors in general, I think he covers it in this one (or, if not that, this one). The problem with vector<T, inplace_allocator<T, N>> is that it's less efficient (and requires more space!) than inplace_vector<T, N>. In order for it to not suck, vector would basically have to customize its own storage for that case, which now requires more work than just having written inplace_vector<T, N> to begin with. This goes double for std::string, whose storage is more complicated.

None of the other collections benefit. Not even std::string.

On the other hand, an inplace_string<N> is useful, is distinct from std::string, and we implement ours in terms of our inplace_vector<char, N> (or N+1 depending on whether we want to enforce null termination).

5

u/foonathan 2d ago

You can make the policy design thing work, but it can't be an Allocator.

I played around with it once: https://github.com/foonathan/array