Topics / C++ for Embedded / Q11
What is placement new and when is it used in embedded code?
Short answer: Placement new (new (address) T(args)) constructs an object in memory you already own — a static buffer, a memory pool slot or a memory-mapped region — without allocating anything. You are then responsible for calling the destructor explicitly (obj->~T()) and for the memory's alignment and lifetime. It is how fixed-capacity containers, std::optional, object pools and "construct later" singletons work without a heap.
#include <cstddef>
#include <cstdio>
#include <new>
class Driver {
public:
explicit Driver(int port) : port_(port) { std::printf("init port %d\n", port_); }
~Driver() { std::printf("deinit port %d\n", port_); }
private:
int port_;
};
alignas(Driver) static std::byte storage[sizeof(Driver)]; // static memory, correct alignment
static Driver *drv;
void driver_start(int port) { drv = new (storage) Driver(port); } // construct in place
void driver_stop() { drv->~Driver(); drv = nullptr; } // explicit destructor call
int main()
{
driver_start(2); // construct after the clocks/board are set up, not before main()
driver_stop();
driver_start(3); // reuse the same storage
driver_stop();
}
Typical uses
- Delaying construction of global objects until hardware is ready (avoids static initialisation order problems).
- Object pools: fixed array of raw storage slots, construct with placement new, destroy explicitly, mark the slot free.
- Fixed-capacity containers (ETL's
etl::vector<T, N>,std::inplace_vectorin C++26).
Rules
- Storage must be correctly aligned (
alignas(T)) and large enough. - Don't call
deleteon a placement-new object; call the destructor. - In modern C++,
std::laundermay be needed when reusing storage for a new object accessed through an old pointer;std::construct_at/std::destroy_at(C++20) are cleaner spellings. - Prefer
std::optional<T>for the simple "maybe constructed" case: it handles storage, alignment and destruction for you.