Search code examples
c++arraysc++11initializationstdarray

Call user defined constructor on elements in std::array


I have a simple example where I create an std::array of some number of Foo elements:

struct Foo
{
     Foo(int bar=0) : m_bar(bar) 
     {
       // Code depending on the value of bar
     }

     int m_bar;
};

const unsigned int num = // get array size 
std::array<Foo, num> fooArr;

When I use the initialiser list in the constructor m_bar(bar) this sets all the Foo.m_bar to 0 (as this is the default constructor parameter value). If I don't do that then it is full with garbage values.

My question is how do I pass in another value different from the default one to the constructor of every element in the array without knowing the array size before hand?

I tried using a init list when creating the array, like so: std::array<Foo, 5> fooArr{3} but that only sets the first element's m_bar to 3.


Solution

  • You should simply default-construct the std::array then use its fill method to populate it with a fixed value. Many compilers can optimize this effectively, so you won't pay for the "extra" initialization.

    To satisfy your use case, the code would look something like this:

    fooArr.fill(Foo(3));