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

34次阅读

共计 567 个字符,预计需要花费 2 分钟才能阅读完成。

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

正文完
 0