Placement new
Placement new constructs an object in storage you already have: new (ptr) T(args). It does not allocate. You end the lifetime with an explicit destructor call ptr->~T(), not with delete.
Detailed Explanation
Ordinary new finds memory and then constructs. Sometimes you already have the memory: a stack buffer, a memory-mapped file, a pool, a vector that did reserve and is about to emplace. Placement new is the construct half.
#include <new> declares void* operator new(std::size_t, void*) which returns the pointer unchanged. new (storage) T(args) constructs T at storage. storage must be aligned for T and large enough. Misaligned placement new is undefined behaviour.
You do not delete the result. delete would free memory you do not own. You call t->~T() to run the destructor, then reuse or free the buffer yourself. If T is trivial, the destructor call is optional but still the honest way to end the lifetime in generic code.
std::vector::emplace_back and std::uninitialized_copy are placement new under the hood. You reach for the raw form when you write an arena, a circular buffer of non-trivial T, or a optional-like type.
Lifetime rules got stricter and clearer in C++20 (std::start_lifetime_as, implicit-lifetime types). The practical rules that always mattered:
- Do not run a constructor twice on the same storage without a destructor in between (unless you are overwriting a trivial type via a legal mechanism).
- Do not use the old object after you placement-new a new one on top of it.
- Storage from
mallocoroperator newis suitable if aligned. Acharstack array needsalignas(T).
new (this) T(...) inside an assignment operator (the "placement-new assign" trick) is fragile: if the constructor throws, this is a husk. Prefer swap or memberwise assign.
construct_at (C++20) is the typed function form: std::construct_at(p, args...). std::destroy_at(p) is the destructor. Prefer them in new code; they are harder to misuse than a raw new expression.
Code Examples
#include <iostream>
#include <new>
#include <string>
int main() {
alignas(std::string) unsigned char buf[sizeof(std::string)];
auto* s = new (buf) std::string("ada");
std::cout << *s << '\n'; // prints: ada
s->~basic_string(); // end lifetime; do not delete
}#include <memory>
#include <string>
int main() {
alignas(std::string) unsigned char buf[sizeof(std::string)];
auto* s = std::construct_at(reinterpret_cast<std::string*>(buf), "al");
std::destroy_at(s);
}Common Gotchas
`delete` on a placement-new pointer
the allocator will free a stack buffer or a pool block. Call the destructor only.
Missing `alignas`
a `char buf[sizeof(T)]` is only alignof(char). Over-aligned types (`long double`, SIMD, some classes) crash or corrupt.
Constructor throws
storage is not "an object". Do not call the destructor. Do not read `T` members.
`vector` already does this
if you are placement-newing into a `vector`'s `data()`, you are probably fighting `emplace_back`.