capypad
0 day streak
cpp / expert
Snippet

Placement New for Manual Memory Management

Placement new allows you to construct an object at a pre-allocated memory address. This is critical for high-performance systems and custom allocators where heap fragmentation or allocation overhead must be avoided.

snippet.cpp
cpp
1
2
3
4
5
char buffer[sizeof(MyClass)];
MyClass* obj = new (buffer) MyClass(42);
 
// Manual cleanup required:
obj->~MyClass();
Breakdown
1
new (buffer) MyClass(42)
Calls the constructor of MyClass using the memory provided by 'buffer' instead of the heap.
2
obj->~MyClass()
Explicitly calls the destructor since 'delete' cannot be used on placement new objects.