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 类型何时进行零初始化?
基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
