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

隐身守侯 提交于 2019-11-27 11:15:42

问题


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 this question a duplicate.

So, I have the following code:

class A {
    public: int _a;
}

void main()
{
    A inst1;
    A* inst2 = new A;
    A* inst3 = new A();
}

_a is left uninitialized in inst1 and inst2 and is initialized to 0 in inst3. Which initialization is called which, and why does the code work as it does? Please take into I account I don't have a C++ 03 standard at hand, but I have the last C++ 11 draft (I'm programming by '03 standard, though), so quotations of the '03 standard or references to '11 are most welcome.

P. S. The original task behind this research was to correctly zeto-initialize a member of arbitrary template type T.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/8106016/c-default-initialization-and-value-initialization-which-is-which-which-is-ca

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!