你是否被面试官问起:“假如我有一块申请好的内存,如何在这块内存上创建我的对象?”
Bro,我经验少,实际工作中压根没用过呀。但答案是可以的,这就是placement new!
形如,
#include <iostream>
#include <new> // Required for placement new
struct MyClass {
int data;
MyClass(int d) : data(d) { std::cout << "Constructor called!\n"; }
~MyClass() { std::cout << "Destructor called!\n"; }
};
int main() {
// 1. Pre-allocate raw memory (no constructor is called yet)
char buffer[sizeof(MyClass)];
// 2. Use placement new to construct the object inside the buffer
MyClass* objPtr = new(buffer) MyClass(42);
// 3. Manually call the destructor when done (critical step!)
objPtr->~MyClass();
return 0;
}