Middle+
Do you know about placement new operator?
sobes.tech AI
Answer from AI
Yes, I know. Placement new allows you to place an object at an already allocated memory address without using standard heap allocation.
Main features:
- Does not allocate memory itself, uses the provided address.
- Calls the object's constructor at the specified address.
- You must manage the object's lifetime yourself (call the destructor).
- Often used with memory pools or pre-allocated memory.
#include <iostream>
#include <new> // for placement new
class MyClass {
public:
int value;
MyClass(int v) : value(v) {
std::cout << "Constructor called, value: " << value << std::endl;
}
~MyClass() {
std::cout << "Destructor called, value: " << value << std::endl;
}
};
int main() {
// Allocate memory manually
char buffer[sizeof(MyClass)];
// Use placement new to create object in buffer
MyClass* obj = new (buffer) MyClass(10);
// Access the object
std::cout << "Object value accessed: " << obj->value << std::endl;
// Call destructor explicitly
obj->~MyClass();
// No need to free memory, as it was allocated on the stack
return 0;
}
Comparison with standard new:
| Feature | new |
placement new |
|---|---|---|
| Memory Allocation | Performs allocation | Does not perform allocation |
| Constructor Call | Calls constructor | Calls constructor |
| Destructor Call | Called with delete |
Must be called explicitly |
| Use Cases | General heap allocation | Memory pools, pre-allocation |