首页
\
问答
\
如何使用placement new运算符创建对象数组?(How do I create array of objects using placement new operator?)
如何使用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; }
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; }
原文:https://stackoverflow.com/questions/42771709
更新时间:2022-04-21 21:04