Coming from a C background, I’ve always assumed the POD types (eg ints) were never automatically zero-initialized in C++, but it seems this was plain wrong!
My understanding is that only ‘naked’ non-static POD values don’t get zero-filled, as shown in the code snippet. Have I got it right, and are there any other important cases that I’ve missed?
static int a;
struct Foo { int a;};
void test()
{
int b;
Foo f;
int *c = new(int);
std::vector<int> d(1);
// At this point...
// a is zero
// f.a is zero
// *c is zero
// d[0] is zero
// ... BUT ... b is undefined
}
Assuming you haven’t modified
abefore callingtest(),ahas a value of zero, because objects with static storage duration are zero-initialized when the program starts.d[0]has a value of zero, because the constructor invoked bystd::vector<int> d(1)has a second parameter that takes a default argument; that second argument is copied into all of the elements of the vector being constructed. The default argument isT(), so your code is equivalent to:You are correct that
bhas an indeterminate value.f.aand*cboth have indeterminate values as well. To value initialize them (which for POD types is the same as zero initialization), you can use: