Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero-initializing elements of a std::array with a default member initializer

Tags:

c++

c++17

Suppose I have a class template like this:

template<typename T, size_t N>
struct S {
   std::array<T,N> a;
};

Is there a default member initializer I can place on a,

template<typename T, size_t N>
struct S {
   std::array<T,N> a = ???;
};

such that no matter what T is, the elements of a will always be initialized (never have indeterminant value)? I.e., even if T is a primitive type like int.

like image 676
Andrew Tomazos Avatar asked Jan 05 '19 13:01

Andrew Tomazos


People also ask

Are std :: array 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).

How do you initialize an array of elements to zero?

Using Initializer List. int arr[] = { 1, 1, 1, 1, 1 }; The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.

Does default constructor zero initialize?

Implicitly defined (by the compiler) default constructor of a class does not initialize members of built-in types.

Does STD array initialize values?

std::array::array default-initialization: Each of the elements is itself default-initialized. For elements of a class type this means that their default constructor is called.


2 Answers

std::array is an aggregate type. You can aggregate initialize it with empty braces {} and that will initialize accordingly the elements of the internal array of T that std::array holds.

like image 197
Jans Avatar answered Oct 24 '22 18:10

Jans


This:

template<typename T, size_t N>
struct S {
   std::array<T,N> a = {};
};

That will recursively copy-initialize each element from {}. For int, that will zero-initialize. Of course, someone can always write:

struct A {
    A() {}
    int i;
};

which would prevent i from being initialized. But that's on them.

like image 29
Barry Avatar answered Oct 24 '22 18:10

Barry