14

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.

2 Answers 2

22

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.

Sign up to request clarification or add additional context in comments.

Comments

8

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.