• 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;

    image.png

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;
}

TianSong
737 声望139 粉丝

阿里山神木的种子在3000年前已经埋下,今天不过是看到当年注定的结果,为了未来的自己,今天就埋下一颗好种子吧