I have a basic program in C++ which lists a given number of primes. The class which does the work is below - my question is, when the input for \"amount\" is 10 (specificall
int* primes = new (nothrow) int[amount]; is using default-initialization, which for scalars like int is a noop (i.e. no actual initialization is performed).
If you want explicit initialization, use value-initialization instead:
int* primes = new (nothrow) int[amount]();
From the C++11 standard, §8.5/6:
To default-initialize an object of type
Tmeans:
- if
Tis a (possibly cv-qualified) class type, the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);- if
Tis an array type, each element is default-initialized;- otherwise, no initialization is performed.
If a program calls for the default initialization of an object of a const-qualified type
T,Tshall be a class type with a user-provided default constructor.
§8.5/7:
To value-initialize an object of type
Tmeans:
- if
Tis a (possibly cv-qualified) class type with a user-provided constructor, then the default constructor forTis called (and the initialization is ill-formed if T has no accessible default constructor);- if
Tis a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, ifT’s implicitly-declared default constructor is non-trivial, that constructor is called.- if
Tis an array type, then each element is value-initialized;- otherwise, the object is zero-initialized.
An object that is value-initialized is deemed to be constructed and thus subject to provisions of this International Standard applying to “constructed” objects, objects “for which the constructor has completed,” etc., even if no constructor is invoked for the object’s initialization.
§8.5/6:
To zero-initialize an object or reference of type
Tmeans:
- if
Tis a scalar type, the object is set to the value0(zero), taken as an integral constant expression, converted toT;- if
Tis a (possibly cv-qualified) non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits;- if
Tis a (possibly cv-qualified) union type, the object’s first non-static named data member is zero-initialized and padding is initialized to zero bits;- if
Tis an array type, each element is zero-initialized;- if
Tis a reference type, no initialization is performed.
And finally from §8.5/10:
An object whose initializer is an empty set of parentheses, i.e.,
(), shall be value-initialized.
(All emphasis mine.)
It is done just for efficiency. Not in all occasions arrays have to be pre-filled with a value, so C++ does not do it by default.
If you use std::vector<int> instead of plain arrays (I recommend you to), you have a constructor to set an initial value that can be 0:
std::vector<int> v(10,0); // 10 elements with 0