简体   繁体   English

C++:使用非默认构造函数动态分配结构的成员数组

[英]C++: dynamically allocating a member array of structs using non-default constructor

If I have:如果我有:

struct a_struct
{
    int an_int;

    a_struct(int f) : an_int(f) {}
    a_struct() : an_int(0) {}
};

class a_class
{
    a_struct * my_structs;

    a_class() {...}
};  

I can do:我可以:

a_class() {my_structs = new a_struct(1)}
//or  
a_class() {my_structs = new a_struct [10]}

But I cannot do:但我不能这样做:

a_class() {my_structs = new a_struct(1) [10]}
//or
a_class() {my_structs = new a_struct() [10]}

Is there any correct syntax to get this to work?有什么正确的语法可以让它工作吗? Or an easy work around?还是一个简单的解决方法?

If using the STL is an option, you could use std::vector instead of a dynamic array.如果使用 STL 是一个选项,您可以使用 std::vector 代替动态数组。

I think that this will work:认为这会起作用:

std::vector<a_struct> my_structs;

my_structs.assign(10, 1);

If not, this should:如果没有,这应该:

my_structs.assign(10, a_struct(1));

You could allocate a raw chunk of memory and use placement new to initialize each struct :您可以分配 memory 的原始块并使用placement new来初始化每个struct

int number_of_structs = 10;
my_structs = (a_struct*)new unsigned char[sizeof(a_struct) * number_of_structs];
     // allocate a raw chunk of memory 
a_struct* p = m_structs;
for (int i=0; i<number_of_structs; i++)
{
    new (p) a_struct(i);
    p++;
}

See also: What uses are there for "placement new"?另请参阅: “放置新”有什么用途?

You could use an array of pointers to pointers.您可以使用指向指针的指针数组。 Then you can create the array that will hold pointers to a_struct(), so you can decide later which constructor to use:然后你可以创建一个数组来保存指向 a_struct() 的指针,这样你就可以稍后决定使用哪个构造函数:

class a_class {
    a_struct ** my_structs;

    a_class() { my_structs = new a_struct* [10]}
    void foo () {
       my_structs[0] = new a_struct(1);
       my_structs[5] = new a_struct("some string and float constructor", 3.14);
    }
}; 

You can't do it directly on any particular parameterized constructor.您不能直接在任何特定的参数化构造函数上执行此操作。 However you can do,不管你怎么做,

a_struct *my_struct[10] = {}; // create an array of pointers

for (int i = 0; i < 10; i++)
    my_struct[i] = new a_struct(i); // allocate using non-default constructor

When you're going to de-allocate the memory,当您要取消分配 memory 时,

for (int i = 0; i < 10; i++)
    delete my_struct[i]  // de-allocate memory

I suggest using a std::vector container instead of going through this process.我建议使用std::vector容器而不是通过这个过程。

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

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