gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:14:52 25 4
gpt4 key购买 nike

给定一个简单的类 MyClass,它的构造函数接受两个 int,我如何在 中初始化一个 MyClass 数组堆

我试过了

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

但这似乎行不通。谢谢

最佳答案

使用 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

请注意,您不必构建所有分配的内容。

或者,更好的是,只需使用 std::vector .

[编辑]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;

它的访问速度稍慢,但更易于使用。

关于C++如何初始化堆中的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8003276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com