r/cpp 6d ago

C++26: std::inplace_vector

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

121 comments sorted by

View all comments

15

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*

47

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(...);

20

u/ChemiCalChems 6d ago

This has finally convinced me that std::optional<T&> is legitimate and useful. Thank you.

16

u/allocallocalloc 6d ago

Welcome to Rust

2

u/tialaramex 5d ago

You were kidding but in fact Rust typically wouldn't do this, it would be usual to instead return None when it worked and Some(thing) when there's no room to push the thing. This is how the Linux kernel's Rust growable arrays (akin to std::vector) work. In userspace it's usually fine to just try to grow the array whenever we need more space but the kernel cannot tolerate surprise allocations - maybe we are the allocator. So we push_within_capacity and the return type is Option<T> because if there was no room we get back the thing there was no room for, and we need to decide what to do about that not just pretend we thought it was fine. APIs which push things but get back a reference to the thing we just pushed do exist in Rust but are less common.

[Edited: reference the correct method name]

7

u/simonask_ 5d ago

If we’re maximizing rustiness, you could let `try_push` return `Result<&mut T, T>`.

A mutable reference to the location of the just appended element, or the element you tried to push by value if it fails. There are a couple of APIs like this in the standard library.