关于c++:C内存管理3placement-new

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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理