r/cpp 6d ago

C++26: std::inplace_vector

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

121 comments sorted by

View all comments

14

u/bartgrumbel 6d ago

I am sure there is a good reason for that, but why is the "optional reference" not simply a pointer? Is that not semantically the same thing, but way easier to deal with.

I.e. why

std::optional<T&>

and not simply

T*

45

u/stilgarpl 6d ago

Optional is monadic, so it's much safer to deal with. You can call it like

inplace_vector.try_push_back(x).or_else(...);

2

u/_Noreturn 5d ago

why don't they add a free function called or_else and still use a ptr?

2

u/jwakely libstdc++ tamer, LWG chair 3d ago

When you chain multiple calls like that it's less clear because of the use of nesting instead of chaining. But mostly because a pointer is still not a reference:

https://brevzin.github.io/c++/2021/12/13/optional-ref-ptr/

An optional ref is simply the more expressive type for these functions and fits the semantics better:

https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2026/p3981r2.html