Default values in C++ initializer lists

前端 未结 3 635
失恋的感觉
失恋的感觉 2020-12-14 03:27

I only just learned yesterday that specifying parameters to initializer list items is optional. However, what are the rules for what happens in this case?

In the bel

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-14 04:07

    Yes, the members will be initialized to zero and a default-constructed object respectively.

    The C++ 11 standard specifies this behavior in 12.6.2/7:

    The expression-list or braced-init-list in a mem-initializer is used to initialize the designated subobject (or, in the case of a delegating constructor, the complete class object) according to the initialization rules of 8.5 for direct-initialization.

    In turn, 8.5/10 reads:

    An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

    Paragraph 8.5/7 defines value-initialized:

    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.

    And finally, 8.5/5 defines zero-initialized:

    To zero-initialize an object or reference of type T means:

    • if T is a scalar type (3.9), the object is set to the value 0 (zero), taken as an integral constant expression, converted to T;
    • if T is a (possibly cv-qualified) non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits;
    • if T is a (possibly cv-qualified) union type, the object’s first non-static named data member is zero- initialized and padding is initialized to zero bits;
    • if T is an array type, each element is zero-initialized;
    • if T is a reference type, no initialization is performed.

提交回复
热议问题