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

Show parent comments

49

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

22

u/ChemiCalChems 5d ago

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

14

u/allocallocalloc 5d 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]

6

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.