C ++空 - 整数成员初始化 - 将内存清零? [英] C++ empty-paren member initialization - zeroes out memory?
问题描述
我最初编写了这样的代码:
I originally wrote some code like this:
class Foo
{
public:
Foo() : m_buffer()
{}
private:
char m_buffer[1024];
};
比我更聪明的人说,使用m_buffer()初始化器会清空内存。我的意图是留下内存未初始化。我没有时间讨论它,但它刺激了我的好奇心。
Someone who is smarter than me said that having the m_buffer() initializer would zero out the memory. My intention was to leave the memory uninitialized. I didn't have time to discuss it further, but it piqued my curiosity.
以前,我一直认为总是列出每个成员在初始化列表是明智的。
Previously, I had thought it was wise to always list each member in the initializer list.
有人可以进一步描述这种行为吗?
Could someone please describe this behavior further?
1)为什么空 - ?
1) Why does the empty-paren initializer fill in memory?
2)它只适用于POD数据类型吗?
2) Does it only hold for POD datatypes? I heard that it was so, but don't have the standard handy.
感谢
推荐答案
如果你有一个初始化的成员,它将值初始化
。对于POD也是如此。对于一个结构,每个成员都是以这种方式初始化的,对于一个数组,它的每个元素都是值初始化的。
If you have a member initialized like that, it will be value-initialized
. That is also true for PODs. For a struct, every member is value-initialized that way, and for an array, every element of it is value-initialized.
价值初始化为一个标量类型,如指针或整数,你将它初始化为 0
类型。所以你会得到空指针或假或任何具体的类型。
Value-initialization for a scalar type like pointer or integer you will have it inialized to 0
converted to the right type. So you will get null pointers or false or whatever type you have concretely.
请注意,规则从C ++ 98改变为C ++ 03(我们现在的),这可能有惊人的效果。 C ++ 98没有值初始化
。它说,默认初始化发生,对于非POD类型总是意味着它的默认构造函数调用。但是如果没有用户声明的构造函数,C ++ 03中的 value-initialization
有特殊的意义:每个元素都是值初始化的。
Note that the rule changed subtly from C++98 to C++03 (what we have right now), which can have surprising effects. C++98 didn't have that value-initialization
. It said default initialization happens, which for a non-POD type always meant it's default constructor invokes. But value-initialization
in C++03 has special meaning if there is no user-declared constructor: Every element is value-initialized then.
这里是区别:
struct A { int c; ~A() { } }; // non-POD, but no user declared ctor
struct B { A a; B():a(){ } } b;
现在,在C ++ 03中,将保证 / code>为零。而在C ++ 98中,
b.a.c
将有一些不确定的值。
Now, in C++03, you will be guaranteed that b.a.c
is zero. While in C++98, b.a.c
will have some indeterminated value.
这篇关于C ++空 - 整数成员初始化 - 将内存清零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!