默认情况下,C++ 结构的成员是否初始化为 0?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1069621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are members of a C++ struct initialized to 0 by default?
提问by Johannes Schaub - litb
I have this struct
:
我有这个struct
:
struct Snapshot
{
double x;
int y;
};
I want x
and y
to be 0. Will they be 0 by default or do I have to do:
我想要x
并且y
是 0。默认情况下它们是 0 还是我必须这样做:
Snapshot s = {0,0};
What are the other ways to zero out the structure?
将结构归零的其他方法是什么?
回答by Johannes Schaub - litb
They are not null if you don't initialize the struct.
如果您不初始化结构,它们就不为空。
Snapshot s; // receives no initialization
Snapshot s = {}; // value initializes all members
The second will make all members zero, the first leaves them at unspecified values. Note that it is recursive:
第二个将使所有成员为零,第一个将它们保留为未指定的值。请注意,它是递归的:
struct Parent { Snapshot s; };
Parent p; // receives no initialization
Parent p = {}; // value initializes all members
The second will make p.s.{x,y}
zero. You cannot use these aggregate initializer lists if you've got constructors in your struct. If that is the case, you will have to add proper initalization to those constructors
第二个将p.s.{x,y}
为零。如果结构中有构造函数,则不能使用这些聚合初始值设定项列表。如果是这种情况,您将不得不为这些构造函数添加适当的初始化
struct Snapshot {
int x;
double y;
Snapshot():x(0),y(0) { }
// other ctors / functions...
};
Will initialize both x and y to 0. Note that you can use x(), y()
to initialize them disregarding of their type: That's then value initialization, and usually yields a proper initial value (0 for int, 0.0 for double, calling the default constructor for user defined types that have user declared constructors, ...). This is important especially if your struct is a template.
将 x 和 y 都初始化为 0。请注意,您可以使用x(), y()
它们来初始化它们而不考虑它们的类型:这就是值初始化,通常会产生一个适当的初始值(0 表示 int,0.0 表示 double,调用用户定义的默认构造函数具有用户声明的构造函数的类型,...)。这很重要,特别是如果您的结构是模板。
回答by JaredPar
No, they are not 0 by default. The simplest way to ensure that all values or defaulted to 0 is to define a constructor
不,默认情况下它们不是 0。确保所有值或默认为 0 的最简单方法是定义一个构造函数
Snapshot() : x(0), y(0) {
}
This ensures that all uses of Snapshot will have initialized values.
这可确保所有 Snapshot 使用都具有初始化值。
回答by bdonlan
In general, no. However, a struct declared as file-scope or static in a function /will/ be initialized to 0 (just like all other variables of those scopes):
一般来说,没有。但是,在函数中声明为文件范围或静态的结构 /will/ 将被初始化为 0(就像这些范围的所有其他变量一样):
int x; // 0
int y = 42; // 42
struct { int a, b; } foo; // 0, 0
void foo() {
struct { int a, b; } bar; // undefined
static struct { int c, d; } quux; // 0, 0
}
回答by AndersK
With POD you can also write
使用 POD,您还可以编写
Snapshot s = {};
You shouldn't use memset in C++, memset has the drawback that if there is a non-POD in the struct it will destroy it.
你不应该在 C++ 中使用 memset,memset 有一个缺点,如果结构中有一个非 POD,它会破坏它。
or like this:
或者像这样:
struct init
{
template <typename T>
operator T * ()
{
return new T();
}
};
Snapshot* s = init();
回答by Adrian Panasiuk
In C++, use no-argument constructors. In C you can't have constructors, so use either memset
or - the interesting solution - designated initializers:
在 C++ 中,使用无参数构造函数。在 C 中你不能有构造函数,所以使用memset
或者 - 有趣的解决方案 - 指定的初始值设定项:
struct Snapshot s = { .x = 0.0, .y = 0.0 };
回答by finnw
Since this is a POD (essentially a C struct) there is little harm in initialising it the C way:
由于这是一个 POD(本质上是一个 C 结构),因此以 C 方式初始化它几乎没有什么害处:
Snapshot s;
memset(&s, 0, sizeof (s));
or similarly
或类似
Snapshot *sp = new Snapshot;
memset(sp, 0, sizeof (*sp));
I wouldn't go so far as to use calloc()
in a C++ program though.
不过,我不会calloc()
在 C++ 程序中使用。
回答by Eric
I believe the correct answer is that their values are undefined. Often, they are initialized to 0 when running debug versions of the code. This is usually not the case when running release versions.
我相信正确的答案是他们的价值观是未定义的。通常,在运行代码的调试版本时,它们被初始化为 0。运行发行版时通常不是这种情况。
回答by Bruno Martinez
Move pod members to a base class to shorten your initializer list:
将 pod 成员移动到基类以缩短初始化列表:
struct foo_pod
{
int x;
int y;
int z;
};
struct foo : foo_pod
{
std::string name;
foo(std::string name)
: foo_pod()
, name(name)
{
}
};
int main()
{
foo f("bar");
printf("%d %d %d %s\n", f.x, f.y, f.z, f.name.c_str());
}