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

后端 未结 4 1035
暖寄归人
暖寄归人 2020-12-10 15:33

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;         


        
4条回答
  •  我在风中等你
    2020-12-10 16:24

    You could allocate a raw chunk of memory and use placement new to initialize each 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

    See also: What uses are there for "placement new"?

提交回复
热议问题