简体   繁体   中英

Default initialization of POD vs. non-POD class types

The C++ standard says (8.5/5):

To default-initialize an object of type T means:

  • If T is a non-POD class type (clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor).

  • If T is an array type, each element is default-initialized.

  • Otherwise, the object is zero-initialized.

With this code

struct Int { int i; };

int main()
{
    Int a;
}

the object a is default-initialized, but clearly ai is not necessarily equal to 0 . Doesn't that contradict the standard, as Int is POD and is not an array ?

Edit Changed from class to struct so that Int is a POD.

From 8.5.9 of the 2003 standard:

If no initializer is specified for an object, and the object is of (possibly cv-qualified) non-POD class type (or array thereof), the object shall be default-initialized; if the object is of const-qualified type, the underlying class type shall have a user-declared default constructor. Otherwise, if no initializer is specified for a nonstatic object, the object and its subobjects, if any, have an indeterminate initial value ); if the object or any of its subobjects are of const-qualified type, the program is ill-formed.

The class you show is a POD, so the highlighted part applies, and your object will not be initialized at all (so section 8.5/5, which you quote, does not apply at all).

Edit: As per your comment, here the quote from section 8.5/5 of the final working draft of the current standard (I don't have the real standard, but the FDIS is supposedly very close):

To default-initialize an object of type T means:

— if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

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

otherwise, no initialization is performed.

Your variable is not initialized. Use

Int a = Int();

to initialize your POD or declare a standard constructor to make it non POD; But you can also use your POD uninitialized for performance reasons like:

Int a;
a.i = 5;

No, the object a is not default-initialized. If you want to default-initialize it, you have to say:

Int a = Int() ;

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