C++ Zero-Initialization

前端 未结 1 1354
醉话见心
醉话见心 2020-12-29 22:19

I\'m having trouble understanding when and why exactly a member in my class is zero-initialized according to http://en.cppreference.com/w/cpp/language/zero_initialization.

相关标签:
1条回答
  • 2020-12-29 22:56

    The following

    MyTest testObj = {};
    

    is not zero-initialization for MyTest, but is simply calling its default constructor. The cppreference page explains why (emphasis mine):

    As part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors, including value initialization of elements of aggregates for which no initializers are provided.

    MyTest is a class type, and a has a constructor.


    Defining the constructor with

    MyTest() = default;
    

    will instead zero-initialize the object.

    Relevant Standard quotes (emphasis mine) below.

    From [dcl.init#8]:

    To value-initialize an object of type T means:

    • if T is a (possibly cv-qualified) class type with either no default constructor ([class.ctor]) 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;

    • ...

    From [dcl.init.list]:

    List-initialization of an object or reference of type T is defined as follows:

    • ...

    • Otherwise, if the initializer list has no elements and T is a class type with a default constructor, the object is value-initialized.

    0 讨论(0)
提交回复
热议问题