简体   繁体   中英

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?

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.

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.xx family. MSVC++ compiler is known to handle () initializers incorrectly in VC6. Newer versions of MSVC++ handle () initializers in accordance with C++98 specification.

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


...
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.

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM