Advertisement
Intermediate C++, Memory Management

What is placement new?

Short answer

Placement new constructs an object at a pre-allocated memory address rather than allocating new memory. It's used to separate allocation from construction (e.g., in custom allocators, memory pools, or containers).

Save C++ mock interview
Advertisement
AModel answer
Placement new constructs an object at a pre-allocated memory address rather than allocating new memory. It's used to separate allocation from construction (e.g., in custom allocators, memory pools, or containers). You must manually call the destructor for placement-new objects; you don't delete them.
alignas(MyClass) char buf[sizeof(MyClass)];
MyClass* p = new (buf) MyClass();  // construct in buf
p->~MyClass();                     // explicit destruction
Real-world example
A memory pool uses placement new to construct objects in a pre-allocated block, avoiding per-object heap calls.
Likely follow-ups
  • How do you destroy a placement-new object? | Where is placement new used?
Related topics