Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 257
Peter Avatar asked Jun 25 '13 12:06

Peter


People also ask

Are std :: arrays zero initialized?

std::array::array For elements of a class type this means that their default constructor is called. For elements of fundamental types, they are left uninitialized (unless the array object has static storage, in which case they are zero-initialized).

Is std :: array initialized?

std::array contains a built-in array, which can be initialized via an initializer list, which is what the inner set is.

Are arrays initialized to zero C++?

The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.

How do you initialize an entire array with value?

int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index. The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list. Designated Initializer: This initializer is used when we want to initialize a range with the same value.


1 Answers

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...?

like image 169
juanchopanza Avatar answered Sep 22 '22 14:09

juanchopanza