In C++, after constructing an object with placement new in a buffer, why must you call its destructor explicitly and never delete it?
answer
- construct without allocating
- the storage belongs to someone else
- p->~T() ends the lifetime
- alignment and size of the buffer
- std::construct_at and std::destroy_at
basics
~20 sPlacement new constructs an object in storage you already own and allocates nothing. delete would also free memory that never came from operator new, which is undefined, so end the lifetime with p->~T() and release the buffer separately.
solid answer
~40 s`::new (static_cast<void*>(slot)) Emitter("sparks", 30)` calls the reserved non-allocating `operator new(std::size_t, void*)`, which just returns the pointer, and then runs the constructor there. Nothing was allocated, so a delete-expression on the result would hand a stack or pool address to `operator delete` - undefined behaviour. Destruction is therefore manual: `e->~Emitter()` runs the destructor and ends the object's lifetime while the bytes stay yours to reuse. The buffer must be large enough and suitably aligned - `alignas(Emitter) std::byte slot[sizeof(Emitter)]` - or construction is undefined. C++17's `std::destroy_at` and C++20's `std::construct_at` wrap both steps, and the latter is usable in constant expressions. Skipping the destructor is allowed only when nothing depends on its side effects; for an `Emitter` holding a `std::string`, it leaks.
code
cpp · 26 lines#include <cstddef>
#include <cstdio>
#include <memory>
#include <new>
#include <string>
struct Emitter {
std::string name;
float rate;
Emitter(std::string n, float r) : name(std::move(n)), rate(r) {}
~Emitter() { std::printf("~Emitter(%s)\n", name.c_str()); }
};
int main() {
// Raw storage with the right size and alignment; no Emitter lives here yet.
alignas(Emitter) std::byte slot[sizeof(Emitter)];
Emitter* e = ::new (static_cast<void*>(slot)) Emitter("sparks", 30.0f); // construct only
std::printf("%s %.0f\n", e->name.c_str(), e->rate);
e->~Emitter(); // destroy only; the storage is not freed
// delete e; // undefined: slot was never obtained from operator new
// C++20 spelling of the same two steps.
Emitter* f = std::construct_at(reinterpret_cast<Emitter*>(slot), "smoke", 5.0f);
std::destroy_at(f);
}go deeper
Recall that placement new builds an object in memory you already have, so you call the destructor yourself and never use delete on it.
Explain the reserved non-allocating operator new, why delete would free foreign storage, and the size and alignment rules for the buffer.
Build pools and in-place storage correctly: alignas byte buffers, reverse-order destruction, std::construct_at and std::destroy_at, and when std::launder is needed.
Confine placement new to a few audited storage types - pools, optional-like buffers - so application code never manages lifetimes by hand.
## What placement new is **Placement new** is a new-expression with extra arguments in parentheses after `new`. The most common form passes a pointer to existing storage: ```cpp alignas(Emitter) std::byte slot[sizeof(Emitter)]; Emitter* e = ::new (static_cast<void*>(slot)) Emitter("sparks", 30.0f); ``` The extra argument selects `operator new(std::size_t, void* ptr)`, one of the standard library's **non-allocating** forms, which simply returns `ptr`. The standard reserves these forms: "a C++ program may not define functions that displace the versions in the C++ standard library". So the expression allocates nothing; it only runs the constructor at that address and yields a typed pointer. The `::` and the cast to `void*` make sure a class-specific `operator new` or an unrelated overload is not picked by accident. ## Why delete is wrong A delete-expression always does two things: destroy, then call a deallocation function. Here the second step has nothing to undo: - `slot` is an automatic array on the stack - or a block inside a pool, a ring buffer or a memory-mapped region; - `operator delete` requires a pointer from a matching `operator new`; handing it any other address is undefined behaviour. So the two halves must be done separately: end the object's lifetime yourself, and release the storage in whatever way it was obtained - by letting the array go out of scope, by returning the block to the pool. ## The explicit destructor call A destructor can be called like a member function: `e->~Emitter()`. This runs the destructor body and member destructors and ends the object's **lifetime**; the storage remains, and you may construct a new object in it afterwards. Rules that go with it: 1. Call it exactly once per constructed object; destroying twice is undefined. 2. Destroy objects in reverse order of construction when several share a buffer. 3. Skipping it is permitted only if the program does not depend on the destructor's side effects - for a type owning a `std::string`, skipping it leaks the string's heap buffer. 4. After destruction, the old pointer must not be used to access an object; a new placement new returns the pointer to use next. C++17 added `std::destroy_at(p)`, which calls `p->~T()` (and destroys arrays element-wise since C++20), and C++20 added `std::construct_at(p, args...)`, equivalent to placement new through a `void*`, usable in constant expressions. They express intent and handle the casts. ## Size, alignment and the buffer Placement new trusts you about the storage: - **Size**: the buffer must have at least `sizeof(T)` bytes. - **Alignment**: the address must satisfy `alignof(T)`. `alignas(T) std::byte slot[sizeof(T)]` guarantees both. A plain `char buf[sizeof(T)]` has alignment 1 and is a classic bug that works on forgiving hardware and fails elsewhere. - **Byte type**: arrays of `unsigned char` or `std::byte` are guaranteed to **provide storage** for objects created inside them; prefer them over other element types. When code reaches a placement-constructed object through a pointer derived from the buffer rather than the pointer placement new returned, `std::launder` can be required; that subtlety is covered with layout and alignment. ## Where it is used | Use | Example | |---|---| | containers separating allocation from construction | `std::vector` reserves raw capacity, constructs elements on `push_back`, destroys on `pop_back` | | optional-like and variant-like storage | an in-place buffer that may or may not hold an object | | object pools in game engines | preallocated slots for particles or projectiles, reused every frame | | static or embedded storage | constructing objects in fixed memory without a heap - covered with static allocation | | arenas | constructing many objects in one block and releasing the block at once | Placement new with extra arguments other than `void*` - for example a custom `operator new(std::size_t, Arena&)` - follows the same expression rules; if its constructor throws, the new-expression calls an `operator delete` with the same extra parameters, if one is declared. ## Interview summary Say it in three sentences: placement new constructs without allocating; therefore you destroy with an explicit destructor call and free the storage by its own mechanism; the buffer must be big enough and aligned. Then mention `std::construct_at` and `std::destroy_at`.
- Why is char buf[sizeof(T)] not a safe buffer for placement new?A `char` array only guarantees alignment 1, so its address may not satisfy `alignof(T)`, and constructing a `T` at a misaligned address is undefined behaviour. Write `alignas(T) std::byte buf[sizeof(T)];` (or `unsigned char`), which fixes alignment and uses a byte type that is guaranteed to provide storage for the new object.
- How does std::vector use placement new and explicit destruction?`reserve` obtains raw storage for capacity elements without constructing them. `push_back` and `emplace_back` construct the next element in place - through the allocator's `construct`, which by default uses placement new or `std::construct_at` - and `pop_back` or `clear` destroy elements explicitly while keeping the storage. Only the vector's destructor or reallocation frees the block.
- Placement new allocates memory inside the buffer
- delete is the right way to destroy a placement-new object
- Any char array of the right size is a valid buffer
- Calling a destructor explicitly frees the object's memory
- You can replace the global operator new(std::size_t, void*) to track placement new
Assumes C++20 for std::construct_at; std::destroy_at is C++17 and placement new itself is unchanged since C++98.