![](/img/trans.png)
[英]Using operator new and placement new to create a dynamic array of non-default constructible objects
[英]How do I create array of objects using placement new operator?
如何使用放置新运算符创建对象数组? 我从其他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;
}
如果要基于new放置设计任何基础结构,则很可能需要创建一个工厂类,以使用RAII在其中构造和存储对象并控制缓冲区。 这样的类\\模式通常称为内存池。 我见过的唯一实际实现的池就是存储具有不同大小和类型的数组和类,并使用特殊的类来存储对此类对象的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.