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;
}
new(buff) Complex[1000]? As in, just add the size of the array to it? Note, however, that placement array new can require more space in a platform dependent way (ick), so a loop calling placement new on each element can be more portable sometiems. Second, why are you overloadingoperator newabove? Is your goal to call a user defined operator new when doing placement new?