How do you construct a C++ object in a static buffer with placement new, and which alignment and lifetime rules must the firmware follow?
answer
- alignas plus an array of std::byte
- keep the pointer new returned
- launder if you recompute it
- destroy_at before reuse
- aligned_storage is deprecated
basics
~10 sReserve alignas(T) std::byte storage[sizeof(T)] with static storage duration, construct with ::new (static_cast<void*>(storage)) T(args), use the pointer new returned, and end the object with std::destroy_at before the storage is reused or reconstructed.
solid answer
~40 sThe buffer must be suitably aligned and big enough: `alignas(PacingConfig) static std::byte config_storage[sizeof(PacingConfig)];` An array of `std::byte` or `unsigned char` **provides storage** for an object created in it, which the standard allows explicitly. Construct with `::new (static_cast<void*>(config_storage)) PacingConfig(lo, hi)`; the global `::new` and the cast to `void*` avoid a class-specific `operator new` or a surprising overload. Keep and use the pointer that expression returns; a pointer recomputed from the buffer with `reinterpret_cast` does not point to the new object until it goes through `std::launder` (C++17). Before reusing the storage or constructing again, end the old object's lifetime with `std::destroy_at` (C++17) or an explicit destructor call. `std::aligned_storage` is deprecated since C++23; spell the buffer with `alignas` instead. C++20's `std::construct_at` does the construction and is also usable in constant expressions.
code
cpp · 29 lines#include <cstddef>
#include <cstdio>
#include <memory>
#include <new>
struct PacingConfig {
int lower_rate_bpm;
int upper_rate_bpm;
PacingConfig(int lo, int hi) : lower_rate_bpm(lo), upper_rate_bpm(hi) {}
};
// Static storage: no heap, sized and aligned for exactly one PacingConfig.
alignas(PacingConfig) static std::byte config_storage[sizeof(PacingConfig)];
static PacingConfig* config = nullptr;
void init_config(int lo, int hi) {
config = ::new (static_cast<void*>(config_storage)) PacingConfig(lo, hi);
}
void shutdown_config() {
std::destroy_at(config); // ends the object's lifetime; the storage stays
config = nullptr;
}
int main() {
init_config(60, 130);
std::printf("%d-%d bpm\n", config->lower_rate_bpm, config->upper_rate_bpm);
shutdown_config();
}go deeper
Know that placement new constructs an object in memory you already own, so no heap is involved.
Size and align the buffer correctly, keep the returned pointer, and destroy the object explicitly.
Explain std::launder, safe reconstruction and how to publish the object to an interrupt handler without races.
Decide whether teams hand-roll placement storage or must use a reviewed wrapper type that encapsulates these rules.
## Why firmware does this A pacemaker-style firmware may not use the heap after start-up, yet some objects cannot be constructed at static-initialization time: their configuration is read from non-volatile memory, or the object must be torn down and rebuilt when the clinician changes the therapy mode. **Placement new** separates the two steps a normal `new` combines: the storage is reserved statically, and the object is constructed in it later, as many times as needed. ## Reserving the storage ```cpp alignas(PacingConfig) static std::byte config_storage[sizeof(PacingConfig)]; ``` Each part matters: - **`sizeof(PacingConfig)`** bytes, so the object fits. - **`alignas(PacingConfig)`**, because a plain byte array is only aligned to 1. Constructing an object at a misaligned address is undefined behaviour, and on many microcontrollers a misaligned word access faults. - **`std::byte` (or `unsigned char`)**: the standard says an array of these types **provides storage** for an object created inside it, so the array's lifetime is not ended by creating the object. - **Static storage duration**, so the bytes exist for the whole program and appear in the memory map. Before C++23 this was often written `std::aligned_storage_t<sizeof(T), alignof(T)>`. That trait is deprecated since C++23; the `alignas` form says the same thing directly. ## Constructing and using the object ```cpp PacingConfig* config = ::new (static_cast<void*>(config_storage)) PacingConfig(60, 130); ``` - The leading `::` selects the global placement form, never a class-specific `operator new`. - The cast to `void*` selects the standard placement overload that takes a `void*` and simply returns it. - **Keep the returned pointer.** It points to the new object. A pointer recomputed from the buffer, `reinterpret_cast<PacingConfig*>(config_storage)`, has the right address but, under the standard's object model, still points to the buffer's first byte; reaching the object through it requires `std::launder` (C++17). Storing the returned pointer once avoids the question. C++20 adds `std::construct_at(p, args...)`, which does the same construction, returns the pointer, and can be used inside constant expressions. ## Ending the object and reusing the storage The storage outlives any one object, so the code must manage the object's lifetime explicitly: 1. Call `std::destroy_at(config)` (C++17) or `config->~PacingConfig()` before the storage is reused or the object is no longer needed. Skipping it is not undefined by itself, but any resource the destructor would release is leaked, and program logic that depends on the destructor's side effects breaks. 2. Never construct a second object over a live one without destroying the first. 3. After destruction, any pointer to the old object is dangling; construct anew and use the new returned pointer. 4. Static storage is not destroyed automatically for objects you placed into it: no destructor runs at program end unless you call it. ## The standard type that already does this For a single object, `std::optional<T>` (C++17) is exactly "aligned storage for one `T` plus a flag saying whether it is alive", with the lifetime rules handled for you: - `static std::optional<PacingConfig> config;` reserves the storage statically; nothing is constructed yet. - `config.emplace(60, 130);` constructs in place, destroying any previous object first. - `config.reset();` runs the destructor. It never allocates, and its destructor runs at program end like any static object. Hand-written placement storage is still needed for arrays of objects constructed one at a time, for storage at a fixed address, or when the flag's extra bytes matter. ## Concurrency and interrupts If an interrupt handler can see the object, publish the pointer only after construction has completed, through a `std::atomic<PacingConfig*>` with a release store, and stop the handler from using it before calling `std::destroy_at`. Placement new provides no synchronization. ## Checklist | Item | Rule | |---|---| | Buffer | `alignas(T) std::byte buf[sizeof(T)]`, static storage duration | | Construct | `::new (static_cast<void*>(buf)) T(args)` or C++20 `std::construct_at` | | Access | the returned pointer; `std::launder` if recomputed from `buf` | | Destroy | `std::destroy_at(p)` before reuse | | Avoid | `std::aligned_storage` (deprecated in C++23), a buffer without `alignas` | The example below runs clean under AddressSanitizer and UndefinedBehaviorSanitizer.
- When is std::launder needed after placement new into a buffer?When you reach the new object through a pointer derived from the buffer, such as `reinterpret_cast<T*>(buf)`, instead of the pointer the new-expression returned. That pointer still points to the buffer's first byte in the object model; `std::launder` (C++17) yields a pointer to the object actually living at that address.
- Why is alignas required on the std::byte buffer?A `std::byte` array has alignment 1, so it may start at any address. If the object type needs 4- or 8-byte alignment, constructing it at a misaligned address is undefined behaviour, and many microcontrollers fault on a misaligned word access. `alignas(T)` gives the buffer the alignment the object needs.
- Any char array large enough can hold any object.
- reinterpret_cast of the buffer always yields a usable object pointer.
- The destructor of a placement-new object runs automatically at scope exit.
- std::aligned_storage is the recommended C++23 spelling.
- Placement new allocates a small block from the heap.
Assumes C++17 for std::launder and std::destroy_at, C++20 for std::construct_at; std::aligned_storage is deprecated since C++23.