When do C++ POD types get zero-initialized?(C++ POD 类型何时进行零初始化?)
问题描述
来自 C 背景,我一直认为 POD 类型(例如 int)在 C++ 中从未自动零初始化,但似乎这是完全错误的!
Coming from a C background, I've always assumed the POD types (eg ints) were never automatically zero-initialized in C++, but it seems this was plain wrong!
我的理解是,只有裸"的非静态 POD 值不会填充零,如代码片段所示.我做对了吗,还有其他重要的案例我遗漏了吗?
My understanding is that only 'naked' non-static POD values don't get zero-filled, as shown in the code snippet. Have I got it right, and are there any other important cases that I've missed?
static int a;
struct Foo { int a;};
void test()
{
int b;
Foo f;
int *c = new(int);
std::vector<int> d(1);
// At this point...
// a is zero
// f.a is zero
// *c is zero
// d[0] is zero
// ... BUT ... b is undefined
}
推荐答案
假设你在调用test()
之前没有修改a
,a
的值为零,因为具有静态存储持续时间的对象在程序启动时被零初始化.
Assuming you haven't modified a
before calling test()
, a
has a value of zero, because objects with static storage duration are zero-initialized when the program starts.
d[0]
的值为零,因为由 std::vector
有一个采用默认参数的第二个参数;第二个参数被复制到正在构造的向量的所有元素中.默认参数是 T()
,所以你的代码等价于:
d[0]
has a value of zero, because the constructor invoked by std::vector<int> d(1)
has a second parameter that takes a default argument; that second argument is copied into all of the elements of the vector being constructed. The default argument is T()
, so your code is equivalent to:
std::vector<int> d(1, int());
b
具有不确定的值是正确的.
You are correct that b
has an indeterminate value.
f.a
和 *c
也有不确定的值.要对它们进行值初始化(对于 POD 类型与零初始化相同),您可以使用:
f.a
and *c
both have indeterminate values as well. To value initialize them (which for POD types is the same as zero initialization), you can use:
Foo f = Foo(); // You could also use Foo f((Foo()))
int* c = new int(); // Note the parentheses
这篇关于C++ POD 类型何时进行零初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ POD 类型何时进行零初始化?


基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01