Default initialization in C++(C++ 中的默认初始化)
问题描述
今天早上我问自己一件事,但我找不到合适的词来谷歌":
I was asking myself something this morning, and I can't find the words to properly "google" for it:
假设我有:
struct Foo
{
int bar;
};
struct Foo2
{
int bar;
Foo2() {}
};
struct Foo3
{
int bar;
Foo3() : bar(0) {}
};
现在如果我 default 实例化 Foo、Foo2 和 Foo3:
Now if I default instantiate Foo, Foo2 and Foo3:
Foo foo;
Foo2 foo2;
Foo3 foo3;
bar 成员在哪种情况下正确初始化?
(好吧,Foo3 显然明确地初始化了它,这里只显示与 Foo2 的区别,所以问题主要是关于前两个.)
(Well Foo3 obviously explicitely initialize it and is only showed here to explicit the difference with Foo2 so the question is mainly about the first two.)
谢谢!:)
推荐答案
只有 foo3 会出现在所有上下文中.foo2 和 foo 将是如果它们是静态持续时间.请注意,Foo 类型的对象在其他上下文中可能初始化为零:
Only foo3 will be in all contexts. foo2 and foo will be if they are of static duration. Note that objects of type Foo may be zero initialized in other contexts:
Foo* foo = new Foo(); // will initialize bar to 0
Foo* foox = new Foo; // will not initialize bar to 0
而 Foo2 不会:
Foo2* foo = new Foo2(); // will not initialize bar to 0
Foo2* foox = new Foo2; // will not initialize bar to 0
这个领域很棘手,C++98 和 C++03 之间的措辞发生了变化,IIRC 又是 C++0X,所以我不依赖它.
that area is tricky, the wording as changed between C++98 and C++03 and, IIRC, again with C++0X, so I'd not depend on it.
有
struct Foo4
{
int bar;
Foo4() : bar() {}
};
bar 也将始终被初始化.
bar will always be initialized as well.
这篇关于C++ 中的默认初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 中的默认初始化
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
