Is new int[10]() valid c++?
arrays, c++, constructor, initialization
Solution
First of all is this valid C++ or is it a microsoft extension?
It is valid in C++, the relevant part of the standard is 5.3.4, with the first paragraph containing the grammar
Is it guaranteed to initialize all the elements of the array?
Yes. Paragraph 5.3.4/15 states that
A new-expression that creates an object of type T initializes that object as follows:
...
- If the new-initializer is of the form (), the item is value-initialized (8.5)
where value initialized for POD means zero-initialize.
Also, is there any difference if I do new int; or new int();? Does the latter guarantee to initialize the variable?
Yes they are different. According with the quote above `new int()` will zero-initialize the integer. In a previous block of the same paragraph:
If the new-initializer is omitted:
If T is a (possibly cv-qualified) non-POD class type (or array thereof), the object is default-initialized (8.5). If T is a const-qualified type, the underlying class type shall have a user-declared default constructor.
Otherwise, the object created has indeterminate value. If T is a const-qualified type, or a (possibly cv-qualified) POD class type (or array thereof) containing (directly or indirectly) a member of const-qualified type, the program is ill-formed;
so `new int` will not initialize the memory.
Problem
While trying to answer this question I found that the code `int* p = new int[10]();` compiles fine with VC9 compiler and initializes the integers to 0. So my questions are: - First of all is this valid C++ or is it a microsoft extension? - Is it guaranteed to initialize all the elements of the array? - Also, is there any difference if I do `new int;` or `new int();`? Does the latter guarantee to initialize the variable?