r/cpp 6d ago

C++26: std::inplace_vector

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

121 comments sorted by

View all comments

13

u/bartgrumbel 5d 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*

44

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

3

u/WHY_DO_I_SHOUT 5d ago

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

1

u/Ameisen vemips, avr, rendering, systems 5d 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*.