C++ default initialization and value initialization: which is which, which is called when and how to reliably initialize a template-type member

前端 未结 2 988
死守一世寂寞
死守一世寂寞 2020-12-13 00:34

My question somewhat overlaps with this and several other similar ones. Those have some great answers, but I\'ve read them and I\'m still confused, so please don\'t consider

相关标签:
2条回答
  • 2020-12-13 01:15

    Not so hard:

    A x;
    A * p = new A;
    

    These two are default initialization. Since you don't have a user-defined constructor, this just means that all members are default-initialized. Default-initializing a fundamental type like int means "no initialization".

    Next:

    A * p = new A();
    

    This is value initialization. (I don't think there exists an automatic version of this in C++98/03, though in C++11 you can say A x{};, and this brace-initialization becomes value-initialization. Moreover, A x = A(); is close enough practically despite being copy-initialization, or A x((A())) despite being direct-initialization.)

    Again, in your case this just means that all members are value-initialized. Value initialization for fundamental types means zero-initialization, which in turn means that the variables are initialized to zero (which all fundamental types have).

    For objects of class type, both default- and value-initialization invoke the default constructor. What happens then depends on the constructor's initializer list, and the game continues recursively for member variables.

    0 讨论(0)
  • 2020-12-13 01:25

    Yes, A inst4 (); is treated as a function declaration. std::string str(); should be the same (i.e. I think you mistakenly thought it worked).

    Apparently (from here), C++03 will have inst3._a be 0, but C++98 would have left it uninitialized.

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