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
.
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).
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.
Implicitly defined (by the compiler) default constructor of a class does not initialize members of built-in types.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With