Search code examples
c++c++11stdarray

Is std::array<int, 10> as class member zero-initialized?


struct MyClass
{
  std::array<int, 10> stdArr;

  MyClass() : stdArr()
  {}
};

MyClass c;

Questions:

  1. Is c.stdArr zero-initialized?
  2. If yes - why?

My own contradictory answers:

  1. It is zero-initialized: std::array wants to behave like a c-array. If in my example above stdArr was a c-array, it would be zero-initialized by stdArr() in the initialization list. I expect that writing member() inside of an initialization list initializes the object.

  2. It's not zero-initialized:

    • std::array normally has a single member which is in my case int[10] _Elems;
    • normally fundamental types and arrays of fundamental types like int[N] are not default-initialized.
    • std::array is an aggregate type which implies that it is default-constructed.
    • because there is no custom constructor which initializes _Elems, I think it is not zero-initialized.

What's the correct behaviour of std::array according to the C++11 Standard?


Solution

  • Is c.stdArr zero-initialized?

    Yes

    If yes - why?

    This performs a value initialization of stdArr:

    MyClass() : stdArr() {}
    

    In this context, the effect of the value initialization is a zero initialization of the object.

    Edit: there is plenty of relevant information in What are Aggregates and PODs...?