问题描述
我的问题与有些重叠,几个其他类似的。这些有一些很好的答案,但我已经阅读他们,我仍然困惑,所以请不要考虑这个问题一式两份。
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();
}
未初始化在
inst1
和 inst2
中,并初始化为 0
inst3
。
调用哪个初始化,为什么代码工作?请考虑我的帐户我手头没有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。这个研究的原始任务是正确地初始化任意模板类型 T
的成员。
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 {};
此外, A x = A();
实际上足够接近,尽管是复制初始化或 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).
对于类类型的对象,default和initialize都调用默认构造函数。然后发生什么取决于构造函数的初始化器列表,并且游戏继续递归的成员变量。
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.
这篇关于C ++默认初始化和值初始化:这是哪个,它被称为何时以及如何可靠地初始化模板类型成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!