5

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.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
senfen
  • 877
  • 5
  • 21
  • 2
    *"Is this total correct to initialize struct by single curly brackets..."* Is a much more general and more difficult question than *"Is it correct to initializing std::array by one pair of curly brackets if zeroed array needed?*" – dyp Mar 18 '15 at 19:51
  • 3
    Yes, that's fine (for `std::array`). You shouldn't have to use double curly brackets either; `std::array arr = {1, 2, 3};` is required to work. – T.C. Mar 18 '15 at 19:51
  • Thanks for the answers, everything is now clear. – senfen Mar 18 '15 at 19:59
  • 1
    This explains a lot... http://stackoverflow.com/questions/11734861/when-can-outer-braces-be-omitted-in-an-initializer-list I believe this changed in C++14. – QuestionC Mar 18 '15 at 20:08

1 Answers1

3

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335