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 类型何时进行零初始化?
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01