Nadir SOUALEM
Nadir SOUALEM

Reputation: 3517

Validity of int * array = new int [size]();

int * array = new int [size]();

The operator() allow to set all values of array to 0 (all bits to 0). it's called value-initialization.

Since which version of g++ is it valid?

What about other compilers?

Where can I find it in standard?

Upvotes: 5

Views: 2218

Answers (3)

AnT stands with Russia
AnT stands with Russia

Reputation: 320631

Initialization with () (including your example) was always a part of standard C++, since C++98. Although there were some changes in the newer versions of the standard, they don't apply to your example.

GCC compilers were known to handle () initializers incorrectly in versions from 2.x.x family. MSVC++ compiler is known to handle () initializers incorrectly in VC6. Newer versions of MSVC++ handle () initializers in accordance with C++98 specification.

Upvotes: 1

James McNellis
James McNellis

Reputation: 355187

This is part of the C++ standard; if it was invalid in g++ then g++ was nonconforming. From the C++ standard (ISO/IEC 14882:2003), several sections are relevant:

5.3.4/15 concerning the new expression says:

If the new-initializer is of the form (), the item is value-initialized

8.5/5 concerning initializers says:

To value-initialize an object of type T means:

— if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

— if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;

— if T is an array type, then each element is value-initialized;

— otherwise, the object is zero-initialized

So, for an array of ints, which are a scalar type, the third and fourth bullet points apply.

Upvotes: 6

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84189

This is from "Working Draft, Standard for Programming Language C++" dated 2009-11-09:

8.5 Initializers
...
7 To value-initialize an object of type T means:

  • if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
  • if T is a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, if T’s implicitly-declared default constructor is non-trivial, that constructor is called.
  • if T is an array type, then each element is value-initialized;
  • otherwise, the object is zero-initialized.

...

Upvotes: 0

Related Questions