senfen
senfen

Reputation: 907

Is it correct to initialize std::array by one pair of curly brackets if zeroed array needed?

I wonder if this construction:

std::array<int, 10> array { };

is equivalent to this:

std::array<int, 10> array { {  } };

Well, both of them compile and both of them give the same result:

for (auto e : array) {
        std::cout << e << ", ";
}

Out:

0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

I know that to initialize std::array by selected values I must use double curly brackets because of aggregate initialization. But I don't know how it behaves with single brackets. So, the question is:

Is this totally correct to initialize struct by single curly brackets in C++11? (this follows that all field of struct will be zeroed)

Edit: As @dyp noted my question in post is more general. Let's assume that my question is about structs with only trivial elements.

Upvotes: 5

Views: 1705

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

According to the C++ Standard (8.5.1 Aggregates)

7 If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized from its brace-or-equal-initializer or, if there is no brace-or-equalinitializer, from an empty initializer list (8.5.4).

and (8.5.4 List-initialization p.#3)

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

Thus initializations

std::array<int, 10> array {};

and

std::array<int, 10> array { {  } };

are equivalent.

Upvotes: 3

Related Questions