- placement new 允许我们将 object 构建于 allocated memory 中;
- 没有所谓 placement delete, 因为 placement new 根本没分配 memory;
亦或称呼与 placement new 对应的 operator delete 为 placement delete。
#include <new> char *buf = new char[sizeof(Complex) * 3]; Complex *pc = new(buf) Complex (1, 2); // ... delete[] buf;
Complex *pc = new(buf) Complex (1, 2);
编译器转换为 ==>
Complex *pc;
try {
void* mem = operator new (sizeof(Complex), buf); // allocate
pc = static_cast<Complex*>(mem); // cast
pc->Complex::Complex(1, 2); // construct
}
catch(std::bad_alloc) {
// 若 allocation 失败就不执行 constructor
}
void* mem = operator new (sizeof(Complex), buf);
源码实现 ==>
void *operator new (size_t, viud *loc)
{
return loc;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。