简体   繁体   English

C ++如何初始化堆中的对象数组

[英]C++ How to initialize an array of objects in the heap

Given a simple class MyClass with a constructor that accepts two int , how can I initialize an array of MyClass in the heap ? 给定一个简单的类MyClass ,其构造函数接受两个int ,如何在堆中初始化MyClass数组?

I've tried 我试过了

MyClass *classes[2] = { new MyClass(1, 2),
                        new MyClass(1, 2) };

But this doesn't seem to work. 但这似乎不起作用。 Thanks 谢谢

Use the std::allocator<MyClass> for this. 为此,请使用std::allocator<MyClass>

std::allocator<MyClass> alloc;
MyClass* ptr = alloc.allocate(2);  //allocate
for(int i=0; i<2; ++i) {
    alloc.construct(ptr+i, MyClass(1, i)); //construct in C++03
    //alloc.construct(ptr+i, 1, i); //construct in C++11
}

//use

for(int i=0; i<2; ++i) {
    alloc.destroy(ptr+i); //destruct
}
alloc.deallocate(ptr); //deallocate

Note that you don't have to construct all that you allocate. 请注意,您不必构造所有分配的内容。

Or, better yet, just use std::vector . 或者,更好的是,只需使用std::vector

[EDIT] KerrekSB suggested this as simpler: [编辑] KerrekSB建议这样做更简单:

MyClass** ptr = new MyClass*[3];
for(int i=0; i<4; ++i)
    ptr[i] = new MyClass(1, i);

//use

for(int i=0; i<4; ++i)
   delete ptr[i];
delete[] ptr;

It's slightly slower access, but much easier to use. 访问速度稍慢,但使用起来更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM