Does a default constructor always initialize all members?

后端 未结 2 1655
抹茶落季
抹茶落季 2020-12-15 07:13

I could swear I don\'t remember having seen this before, and I\'m having trouble believing my eyes:

Does an implicitly-defined default constructor for a non-aggregat

2条回答
  •  再見小時候
    2020-12-15 08:02

    (All quotes in the first section are from N3337, C++11 FD with editorial changes)

    I cannot reproduce the behavior with the VC++ on rextester. Presumably the bug (see below) is already fixed in the version they are using, but not in yours - @Drop reports that the latest release, VS 2013 Update 4, fails the assertion - while the VS 2015 preview passes them.

    Just to avoid misunderstandings: S is indeed an aggregate. [dcl.init.aggr]/1:

    An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

    That is irrelevant though.
    The semantics of value initialization are important. [dcl.init]/11:

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

    [dcl.init]/8:

    To value-initialize an object of type T means:

    • if T is a (possibly cv-qualified) class type (Clause 9) with either no default constructor (12.1) or a default constructor that is user-provided or deleted, then the object is default-initialized;
    • if T is a (possibly cv-qualified) class type without a user-provided or deleted default constructor, then the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object is default-initialized;
    • [..]

    Clearly this holds regardless of whether b is in S or not. So at least in C++11 in both cases a should be zero. Clang and GCC show the correct behavior.


    And now let's have a look at the C++03 FD:

    To value-initialize an object of type T means:

    • if T is a class type (clause 9) with a user-declared constructor (12.1) [..]
    • 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

    That is, even in C++03 (where the above quote in [dcl.init]/11 also exists in /7), a should be 0 in both cases.
    Again, both GCC and Clang are correct with -std=c++03.

    As shown in hvd's answer, your version is compliant for C++98, and C++98 only.

提交回复
热议问题