2

Let's suppose I have a class template that has a std::array member:

template<typename T>
class C {
public:
    C();

private:
    std::array<T, 42> a;
};

How do I define C::C such that a will always be value-initialized (not default-initialized)? ie such that the constructor calls T() to initialize every element of a - and that, for example, if T is int, then every element of a is guaranteed to be zero and not an indeterminant value?

int main() {
   C<int> c;
   assert(c.a[13] == 0); // ignoring private for exposition
}

UPDATE

Additional information for posterity:

  1. std::array is an aggregate type with a single element T[N]
  2. Initialization of std::array by an init-list is aggregate initialization
  3. Aggregate initialization with an empty init-list causes each element to not be explicitly initialized. Such elements are initialized as if by copy-initialization from an empty init-list.
  4. The array T[N] is therefore copy-initialized from an empty init-list. It is also an aggregate therefore 2 and 3 apply recursively.
  5. Each of the N elements of T[N] are copy-initialized from an empty init-list.
  6. Each T object is copy-list-initialized with an empty init-list as per [dcl.init.list]/3. The final clause of that chain is reached which reads:

Otherwise, if the initializer list has no elements, the object is value-initialized.

and voila. Initializing std::array with an empty init list {} causes its elements to be value-initialized.

1 Answer 1

4

You can use inline member initialization:

private:
    std::array<T, 42> a{};

If you absolutely want to do it with a constructor instead (why though?) then:

C()
    : a{}
{ }
Sign up to request clarification or add additional context in comments.

9 Comments

How does that look in a definition of C::C ? (ie the question asks for a definition of C::C)
@AndrewTomazos what do you mean? You don't need anything special in the constructor definition.
The question asks for a definition of C::C - ie an answer should start with C::C() /*...*/, not using a default member initializer.
ie Does C::C() : a{} {} do the same thing and would it also work?
@AndrewTomazos this can be solved as well, like with C() : a{func_returning_array()} {}
|

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.