Sreeraj Chundayil
Sreeraj Chundayil

Reputation: 5859

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

How do I create array of objects using placement new operator? I know how to do it for single object from other SO questions. But I couldn't find for array of objects.

To see the performance difference I am trying to create an array of objects and deleting after the subloop. But I am not able to find a way. How do I create multiple objects?

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

Upvotes: 0

Views: 1072

Answers (1)

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14589

What's the purpose of overriding a standard-defined new operator to rather useless function? And how you suppose to store pointers if you create one by one

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

If you going to design any infrastructure based on placement new , you most likely need to create a factory class to construct and store obejcts in and to control the buffer, using RAII. Such classes\patterns are generally called memory pools. The only practical pool I ever saw implemented was storing arrays and classes of different size and type, using special class to store a reference to such object.

Upvotes: 2

Related Questions