如何在构造函数中初始化具有相同值的对象数组

时间:2015-09-03 22:58:08

标签: c++ arrays constructor

我正在尝试初始化具有相同值的对象数组

class A
{
   A(int a1)
   {
      var1 = a1;
   }

   var1;
}

int main(void)
{
    // I want to initialize all the objects with 5 without using an array 
    A *arr = new A[10](5); // How to use the constructor to do something like this
    return 0;
}

因为我想将相同的值传递给所有对象,是否有办法避免使用数组。即我想避免做以下事情:

A *arr = new A[10]{5, 5, 5, 5, 5, 5, 5, 5, 5, 5}

1 个答案:

答案 0 :(得分:4)

通常我们会避免使用原始指针,尤其是在没有封装在std::unique_ptr或其他自动(RAII)指针类型中时。

如果编译时已知大小,则首选std::array;如果需要动态大小或非常大的数组,则为std::vector

如果您坚持自己管理内存,第二个选择是使用std::fill中的std::fill_n<algorithm>

在这种情况下,std::fill_n可能更清晰:

A *arr = new A[10];
std::fill_n( &arr[0], 10, A(5) );

请至少考虑自动指针管理:

std::unique_ptr<A[]> arr( new A[10] );
std::fill_n( &arr[0], 10, A(5) );