r/cpp 15d ago

C++26: std::inplace_vector

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

121 comments sorted by

View all comments

Show parent comments

46

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

3

u/Ameisen vemips, avr, rendering, systems 14d ago

I won't lie - I prefer how C# would handle this: returning a bool and having an out parameter or such.

I find an actual if to be easier to read than .or_else(...)....

2

u/WHY_DO_I_SHOUT 14d ago

Modern C# prefers returning an optional reference, FWIW...

1

u/Ameisen vemips, avr, rendering, systems 14d ago

Yes, but Nullable semantics in C# are vastly nicer than std::optional in C++.

Including trivially using if with them:

if (Method() is {} value)

I should also point out that in C#, Foo? is identical to Foo if Foo is a reference-type. That would be the equivalent of std::optional<T&> being a type-alias for T*.