I'm quite certain that arrays of built in types are unitialized, whereas arrays of UDTs are default initialized.
int foo[5]; // will contain junk
Foo foo[5]; // will contain 5 Foo objects that are default initialized
This occurs regardless of whether the array is allocated on the stack or heap.
However, I'm finding it hard to find an authoritative source on this. Bjarne states that:
"Members of arrays and structures are default initialized or not depending on whether the array or structure is static" which doesn't really tell me too much.
I've also tried to find something in the standard, but so far no to no avail.
Does anyone know of an authoritative source to confirm the above?
Best Answer
ISO C++03 is about as authoritative as it gets:
For your example,
int
is definitely a POD type (it's an arithmetic type), and therefore a local or field of typeint
, in the absence of initializer, will have an indeterminate value. ForFoo
, this depends on how it is defined - roughly speaking, if it doesn't have a constructor, and all its members are of POD types, then it is itself a POD type, and no initialization takes place either. Otherwise, the default constructor is called. Even then, this doesn't mean that members are initialized - rules are recursive, so POD members of non-POD type won't be initialized unless the constructor of that type specifically does that (in its initializer list).Static variables and fields will in all cases be zero-initialized. Note that this applies to non-PODs too - meaning that a static variable of a class type is guaranteed to have all fields recursively set to
(T)0
even before its constructor runs.A handy trick to default-initialize any aggregate POD type is to use
{}
in initializer - note that it works with structs as well as arrays: