如何使用 placement new 运算符创建对象数组?

How do I create array of objects using placement new operator?

如何使用 placement new 运算符创建对象数组? 我知道如何从其他 SO 问题中为单个对象执行此操作。 但是我找不到对象数组。

为了查看性能差异,我尝试创建一个对象数组并在子循环之后删除。但我找不到办法。 如何创建多个对象?

class Complex
{
  double r; // Real Part
  double c; // Complex Part

  public:
    Complex() : r(0), c(0) {}
    Complex (double a, double b): r (a), c (b) {}
    void *operator new( std::size_t size,void* buffer)
    {
        return buffer;
    }
};

char *buf  = new char[sizeof(Complex)*1000]; // pre-allocated buffer

int main(int argc, char* argv[])
{
  Complex* arr;
  for (int i = 0;i < 200000; i++) {
    //arr = new(buf) Complex(); This just create single object.
    for (int j = 0; j < 1000; j++) {
      //arr[j] = Now how do I assign values if only single obect is created?
    }
    arr->~Complex();
  }
return 0;
}

将标准定义的新运算符覆盖为无用函数的目的是什么?如果你一个一个地创建,你应该如何存储指针

#include <iostream>

class Complex
{
  double r; // Real Part
  double c; // Complex Part

  public:
    Complex() : r(0), c(0) {}
    Complex (double a, double b): r (a), c (b) {}
};

char *buf  = new char[sizeof(Complex)*1000]; // pre-allocated buffer

int main(int argc, char* argv[])
{ 
    // When doing this, it's _your_ problem 
    // that supplied storage  is aligned proeperly and got 
    // enough storage space

    // Create them all
    // Complex* arr = new(buf) Complex[1000];

    Complex** arr = new Complex*[1000];
    for (int j = 0; j < 1000; j++)      
        arr[j] = new (buf + j*sizeof(Complex)) Complex;

    for (int j = 0; j < 1000; j++) 
        arr[j]->~Complex();

    delete[] buf;
    return 0;
}

如果您要根据 placement new 设计任何基础设施,您很可能需要创建一个工厂class来构造和存储对象并控制缓冲区,使用 RAII。这样的classes\patterns一般称为内存池。我见过的唯一实用的池是存储数组和不同大小和类型的 classes,使用特殊的 class 来存储对此类对象的引用。