什么时候C ++ POD类型得到零初始化? [英] When do C++ POD types get zero-initialized?
问题描述
来自C的背景,我一直假设POD类型(例如int)永远不会自动零初始化在C + +,但似乎这是完全错误!
我的理解是,只有'裸体'非静态POD值不会得到零填充,如代码片段所示。我有没有错,还有其他重要的情况,我错过了吗?
static int a;
struct Foo {int a;};
void test()
{
int b;
Foo f;
int * c = new(int);
std :: vector< int> d(1);
//此时...
// a为零
// fa为零
// * c为零
// d [0]为零
// ... BUT ... b未定义
}
<假设您在调用 test()之前未修改
c $ c>, a
a值为零,因为具有静态存储持续时间的对象在程序启动时为零初始化。
d [0]
的值为零,因为 std :: vector< int> d(1)
有一个带有默认参数的第二个参数;将第二个参数复制到正在构造的向量的所有元素中。默认参数为 T()
,因此您的代码等效于:
std :: vector< int> d(1,int());
您确定 b
值。
fa
和 * c
值。要值初始化它们(对于POD类型与零初始化相同),您可以使用:
Foo f = Foo ); //你也可以使用Foo f((Foo()))
int * c = new int(); //注意括号
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!
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
}
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]
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());
You are correct that b
has an indeterminate value.
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类型得到零初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!