Without a heap, why is std::array plus a count a weak fixed-capacity container in C++, and what does C++26 std::inplace_vector change?
answer
- every slot is constructed up front
- needs a default constructor
- a capacity fixed at compile time
- try_push_back reports a full buffer
- freestanding-deleted members
basics
~20 sstd::array constructs all N elements up front, so the type needs a default constructor and unused slots hold live objects. C++26 std::inplace_vector constructs elements only on insertion, and try_push_back reports a full container without throwing.
solid answer
~40 s`std::array<T, N>` is an aggregate with all `N` elements alive for its whole lifetime. Used as a fixed vector with a separate count, it must default-construct every slot up front (the example constructs 32 `Reading` objects before the first push), `T` must be default-constructible, "removing" an element leaves a live object behind, and the count is a second variable that can drift. C++26's `std::inplace_vector<T, N>` is the standard fixed-capacity vector: storage for `N` elements lives inside the object, elements are constructed only when inserted and destroyed when erased, and capacity never changes. `push_back` throws `std::bad_alloc` when full, so firmware uses `try_push_back`, which returns an empty `std::optional<T&>` instead (the C++26 draft's return type; earlier drafts returned a pointer), or `unchecked_push_back` when fullness is already known. libstdc++ in GCC 16 ships it; libc++ does not yet.
code
cpp · 27 lines#include <array>
#include <cstddef>
#include <cstdio>
static int constructed = 0;
struct Reading {
int millivolts;
Reading() : millivolts(0) { ++constructed; }
explicit Reading(int mv) : millivolts(mv) { ++constructed; }
};
std::array<Reading, 32> readings; // all 32 elements constructed at start-up
std::size_t count = 0; // how many are "really" in use
bool push(int mv) {
if (count == readings.size()) return false; // full: caller decides
readings[count++] = Reading(mv); // assigns over a live element
return true;
}
int main() {
std::printf("constructed before any push: %d\n", constructed);
push(812);
push(790);
std::printf("in use: %zu of %zu, constructed: %d\n", count, readings.size(), constructed);
}go deeper
Know that std::array has a fixed number of live elements and that C++26 adds inplace_vector for a variable size within a fixed capacity.
Explain the costs of array plus count and how inplace_vector constructs elements only on insertion.
Choose between push_back, try_push_back and unchecked_push_back in a build without exceptions, and track the late change to try_push_back's return type.
Decide whether to adopt inplace_vector now, wrap it, or keep an in-house type until every target library ships it.
## What firmware needs from a container Pacing firmware keeps a log of recent events, a queue of pending telemetry packets, a list of active alerts. Each has a known worst-case size and must never touch the heap. What the code wants is a **vector with a fixed capacity**: storage reserved inside the object, a size that goes up and down, elements constructed and destroyed individually, and a clear answer when it is full. ## Why std::array plus a count is weak `std::array<T, N>` is an aggregate wrapping `T[N]`, and all `N` elements exist for the array's whole lifetime. Turning it into a vector by adding a `count` variable has several costs: - **Every slot is constructed up front.** The example constructs 32 `Reading` objects at start-up before any reading is pushed, and each push then assigns over a live object (34 constructions for two pushes). - **The element type needs a default constructor**, or the array must be initialized with `N` explicit values. A type that cannot be meaningfully default-constructed, such as one holding a reference or a hardware handle, does not fit. - **"Removed" elements stay alive.** Decrementing `count` does not run a destructor, so a slot can keep holding a resource. - **Two sources of truth.** `count` and the array can disagree after a bug, and every algorithm must remember to use `begin()` to `begin() + count`, not the whole array. These are acceptable for an array of integers and become real problems for richer element types. ## The hand-written alternative Before C++26, firmware teams wrote their own fixed vector: an `alignas(T) std::byte storage[N * sizeof(T)]` buffer, placement new to construct an element on insertion, `std::destroy_at` on removal, and a size member. It works, but each team re-implements lifetime rules that are easy to get subtly wrong, which is why a standard type was added. ## std::inplace_vector in C++26 The C++26 final draft (N5050) adds `<inplace_vector>` with `template<class T, size_t N> class inplace_vector;`: - **Storage inside the object.** No allocator, no heap; `capacity()` is always `N`. - **Construct on insertion.** Elements are constructed when inserted and destroyed when erased; `T` needs no default constructor. - **Three ways to append**, which matter in firmware: | Member | When full | Return type in N5050 | |---|---|---| | `push_back`, `emplace_back` | throws `std::bad_alloc` | `reference` | | `try_push_back`, `try_emplace_back` | no effect, returns `nullopt` | `optional<reference>` | | `unchecked_push_back`, `unchecked_emplace_back` | precondition violation | `reference` | The `try_` return type changed late: paper P3981R2, applied in 2026, replaced the earlier pointer return with `std::optional<T&>`, and P4022R0 removed `try_append_range` for now. Code written against an older draft or an early implementation may still expect a pointer. ```cpp // C++26, not compiled here: libc++ in LLVM 23 lacks <inplace_vector> #include <inplace_vector> std::inplace_vector<Reading, 32> readings; // nothing constructed yet if (!readings.try_push_back(Reading{812})) { record_overrun(); // full: no exception, no allocation } ``` ## Costs that differ from std::vector A fixed-capacity container trades heap use for other costs a reviewer should know: - **Size.** `sizeof(std::inplace_vector<T, N>)` includes room for all `N` elements, so a large capacity in a stack frame can overflow a small stack. - **Moves are linear.** A `std::vector` move steals a pointer; moving an `inplace_vector` moves each element, because the elements live inside the object. - **Triviality is kept.** The C++26 draft says that if `T` is trivially copy constructible, so is `inplace_vector<T, N>`'s copy constructor, and likewise for moves and destruction, so a buffer of plain bytes can be copied with no per-element code. ## Freestanding and exception-free builds `std::inplace_vector` is listed among the C++26 freestanding headers, but only partially: members that report errors by throwing, such as `push_back` and `at`, are marked **freestanding-deleted**, meaning a freestanding implementation may provide them as deleted functions. The `try_` and `unchecked_` members are the ones a firmware build without exceptions is meant to use. ## Choosing today 1. On a C++26 library that provides it, use `std::inplace_vector` with `try_push_back`. 2. Otherwise, use a well-tested in-house or third-party fixed vector with the same interface, so the later switch is mechanical. 3. Keep `std::array` for tables that are always full, such as calibration data, where its all-elements-alive model is exactly right.
- What happens when std::inplace_vector::push_back is called on a full container?The C++26 draft says it throws `std::bad_alloc`, with no effect on the container. That is why firmware built without exceptions uses `try_push_back`, which returns `nullopt` when full, or `unchecked_push_back` when the caller has already checked `size() < capacity()`.
- Why is a hand-written fixed vector easy to get wrong?It manages object lifetime by hand: placement new into aligned raw storage on insertion, `std::destroy_at` on removal, correct copy and move of only the live elements, and no access to slots that hold no object. Each of those is a place for undefined behaviour that a standard type has already got right.
- std::array only constructs the elements you have pushed.
- std::inplace_vector allocates when it runs out of capacity.
- inplace_vector::try_push_back throws when the container is full.
- Lowering a count variable destroys the removed std::array element.
- std::inplace_vector is available in every C++23 library.
Assumes C++26 (final draft N5050) for std::inplace_vector, with P3981R2's optional<T&> return; anchored at C++23, the current published standard.