C++默认初始化和值初始化:哪个是哪个,什么时候调用以及如何可靠地初始化一个模板类型成员

2022-01-18 00:00:00 initialization default-value c++

我的问题与 this 和其他几个类似的.这些有一些很好的答案,但我已经阅读了它们,但我仍然感到困惑,所以请不要认为这个问题是重复的.

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.

所以,我有以下代码:

class A {
    public: int _a;
}

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

_ainst1inst2 中未初始化,在 inst3<中初始化为 0/代码>.哪个初始化被称为哪个,为什么代码会这样工作?请考虑到我手头没有 C++ 03 标准,但我有最后的 C++ 11 草案(不过我正在按照 '03 标准编程),所以引用 '03 标准或引用 '11非常欢迎.

_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. 这项研究的最初任务是正确地对任意模板类型 T 的成员进行 zeto 初始化.

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

推荐答案

没那么难:

A x;
A * p = new A;

这两个是默认初始化.由于您没有用户定义的构造函数,这仅意味着所有成员都是默认初始化的.默认初始化像 int 这样的基本类型意味着没有初始化".

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".

下一步:

A * p = new A();

这是值初始化.(我认为在 C++98/03 中不存在这个的自动版本,尽管在 C++11 中你可以说 A x{};,而这个 brace-初始化 变成了值初始化.此外,A x = A(); 尽管是 copy-initialization 或 A x((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.

相关文章