【问题标题】:C++: dynamically allocating a member array of structs using non-default constructorC++:使用非默认构造函数动态分配结构的成员数组
【发布时间】:2011-09-03 00:18:55
【问题描述】:

如果我有:

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() {...}
};  

我能做到:

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

但我不能这样做:

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

是否有任何正确的语法可以让它工作?还是一个简单的解决方法?

【问题讨论】:

    标签: c++ arrays constructor struct memory-management


    【解决方案1】:

    如果使用 STL 是一个选项,您可以使用 std::vector 代替动态数组。

    认为这会奏效:

    std::vector<a_struct> my_structs;
    
    my_structs.assign(10, 1);
    

    如果不是,这应该:

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

    【讨论】:

    • 或者只是std::vector&lt;a_struct&gt; my_structs(10, 1);
    【解决方案2】:

    您可以分配一块原始内存并使用 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++;
    }
    

    另请参阅:What uses are there for "placement new"?

    【讨论】:

      【解决方案3】:

      您可以使用指向指针的指针数组。然后你可以创建一个数组来保存指向 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);
          }
      }; 
      

      【讨论】:

      • 这不允许您传递结构数组(或指向结构的指针,然后使用指针数学移动到数组的下一个元素)。
      【解决方案4】:

      您不能直接在任何特定的参数化构造函数上执行此操作。不管你怎么做,

      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
      

      当你要释放内存时,

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

      我建议使用std::vector 容器而不是通过此过程。

      【讨论】:

      • 在这种情况下std::vector的优点是所有my_structs都将在一个连续的内存块中。
      • 这不允许您传递结构数组(或指向结构的指针,然后使用指针数学移动到数组的下一个元素)
      猜你喜欢
      • 1970-01-01
      • 2016-12-16
      • 2011-01-06
      • 2018-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      • 2016-07-28
      相关资源
      最近更新 更多