1

Just switched to C++11 from C++03, and I was wondering, is the following defined to always zero initialize the array data for all elements?

template<size_t COUNT>
class Test {
public:
    uint32 data[COUNT] = {};
};
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Anne Quinn
  • 12,609
  • 8
  • 54
  • 101
  • 2
    As a side note, if you just upgraded to C++11, then you might as well upgrade to C++14 already. – tambre Sep 03 '17 at 10:42
  • 4
    Yes, however if you switching to C++11 you should also use `::std::array` instead of plain C arrays and there is not need to place `=` in between unless you need to avoid accidental call to explicit constructor. – user7860670 Sep 03 '17 at 10:44
  • @tambre - oh, I have actually, I must've mentioned C++11 out of habit (I've been stuck in 03 for, well, years now, aha) – Anne Quinn Sep 03 '17 at 10:45
  • 1
    Fun fact, you can do direct initialization for the array instead of copy initialization: `uint32 data[COUNT] {};` – StoryTeller - Unslander Monica Sep 03 '17 at 10:50
  • @AnneQuinn I believe that `uint32 data[COUNT] = {};` zero-initializes the array in C++03 as well, see [this](https://stackoverflow.com/a/201116/3093378), although C++03 does not allow in-class member initialization. – vsoftco Sep 03 '17 at 12:28

1 Answers1

3

Yes it's guaranteed; list initialization turns to aggregate initialization for array type:

Otherwise, if T is an aggregate type, aggregate initialization is performed.

then for aggregate initialization:

If the number of initializer clauses is less than the number of members or initializer list is completely empty, the remaining members are initialized by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates).

So all the elements of data will be value initialized, for uint32 they'll be zero-initialized at last.

otherwise, the object is zero-initialized.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405