问题描述
来自 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 类型何时进行零初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!