Initializing Default POD and Non-POD Types

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

To initialize an object of type T by default:

  • If T is a non-POD class type (section 9), the default constructor for T is called (and initialization is poorly formed if T does not have an available default constructor).

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

  • Otherwise, the object is initialized to zero.

Using this code

 struct Int { int i; }; int main() { Int a; } 

object a initialized by default, but it is clear that ai not necessarily 0. Is this not against the standard, since Int is a POD and is not an array?

Change Changed from class to struct , so Int is a POD.

+4
source share
3 answers

From 8.5.9 of the 2003 standard:

If the object does not have an initializer, and the object has a value (possibly cv-qualified) of the non-POD class type (or its array), the object should be initialized by default; if the object has a const-qual type, the base class type must have a default constructor declared by the user. Otherwise, if the initializer is not set for an object that is not an object, the object and its subobjects, if any, have an undefined initial value ); if an object or any of its subobjects has a const-qualified type, the program is poorly formed.

The class you are showing is the POD, so the highlighted part is applied and your object will not be initialized at all (so the section 8.5 / 5 that you quote is not applied at all).

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

To initialize an object of type T by default:

- if T is (possibly cv-qualified) (type 9), the default constructor for T (and initialization is poorly formed if T does not have a default constructor available);

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

- , otherwise, initialization is not performed.

+6
source

Your variable is not initialized. Use

 Int a = Int(); 

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

 Int a; ai = 5; 
+1
source

No, object a not initialized by default. If you want to initialize it by default, you should say:

 Int a = Int() ; 
0
source

Source: https://habr.com/ru/post/1382875/


All Articles