C++ typedef 结构:默认初始化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3153725/
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
typedef struct : Default Initialization
提问by Stephen Blinkhorn
typedef struct foo
{
bool my_bool;
int my_int;
} foo;
In the example above I understand that my_boolwill be initialized randomly to either true or false but what about my_int? I assumed that my_intwould be default initialized to 0 but that seems not to be the case.
在上面的例子中,我知道my_bool将被随机初始化为 true 或 false 但是my_int呢?我认为my_int将默认初始化为 0 但似乎并非如此。
Defining structs in this way appears to be incompatible with initialization lists so what is the best way to initialize my_booland my_intto false and 0 respectively?
以这种方式定义结构似乎与初始化列表不兼容,那么将my_bool和my_int分别初始化为 false 和 0的最佳方法是什么?
回答by AnT
Types don't get "initialized". Only objectsof some type get initialized. How and when they get initialized depends on how and where the corresponding object is defined. You provided no definition of any object in your question, so your question by itself doesn't really make much sense - it lacks necessary context.
类型不会“初始化”。只有某种类型的对象会被初始化。它们初始化的方式和时间取决于定义相应对象的方式和位置。您在问题中没有提供任何对象的定义,因此您的问题本身并没有多大意义 - 它缺乏必要的上下文。
For example, if you define a static object of type foo
例如,如果您定义类型为的静态对象 foo
static foo foo_object; // zeros
it will be automatically zero-initialized because all objects with static duration are always automatically zero-initialized.
它将自动零初始化,因为所有具有静态持续时间的对象总是自动零初始化。
If you define an automatic object of type foo
without an initializer, it will remain uninitialized
如果你定义一个foo
没有初始化器的自动类型对象,它将保持未初始化状态
void func()
{
foo foo_object; // garbage
}
If you define an automatic object of type foo
with an aggregate initializer, it will be initialized in accordance with that initializer
如果foo
使用聚合初始化器定义类型的自动对象,它将根据该初始化器进行初始化
void func()
{
foo foo_object1 = { 1, 2 }; // initialized
foo foo_object2 = {}; // initialized with zeros
}
If you allocate your object with new
and provide no initializer, it will remain uninitialized
如果您分配对象但new
不提供初始化程序,它将保持未初始化状态
foo *p = new foo; // garbage in `*p`
But if you use the ()
initializer, it will be zero-initialzed
但是如果你使用()
初始化器,它会被零初始化
foo *p = new foo(); // zeros in `*p`
If you create a temporary object of type foo
using the foo()
expression, the result of that expression will be zero-initialized
如果您foo
使用该foo()
表达式创建一个临时对象类型,则该表达式的结果将被零初始化
bool b = foo().my_bool; // zero
int i = foo().my_int; // zero
So, once again, in your specific case the initialization details depend on now you create the object of your type, not on your type itself. Your type itself has no inherent initialization facilities and doesn't interfere with the initialization in any way.
因此,再一次,在您的特定情况下,初始化细节取决于您现在创建的类型的对象,而不是您的类型本身。您的类型本身没有固有的初始化设施,并且不会以任何方式干扰初始化。
回答by rturrado
Implement a default constructor:
实现一个默认构造函数:
typedef struct foo
{
foo()
: my_bool(false), my_int(0)
{
// Do nothing
}
bool my_bool;
int my_int;
} foo;
回答by Cogwheel
First off, the way that struct is declared is in the style of C. In C++ you should just do:
首先,struct 的声明方式是 C 风格的。在 C++ 中,你应该这样做:
struct foo
{
bool my_bool;
int my_int;
};
In both C and C++, initialization is a separate step from allocation. If you always want to initialize the members of your struct, use default initialization syntax like this:
在 C 和 C++ 中,初始化与分配是分开的步骤。如果您总是想初始化结构的成员,请使用这样的默认初始化语法:
struct foo
{
bool my_bool{};
bool my_int{};
};
In older versions of C++ you need to manually write a default constructor that initializes all the members (the newer syntax above is just sugar for this):
在旧版本的 C++ 中,您需要手动编写一个默认构造函数来初始化所有成员(上面较新的语法只是为此而做的糖):
struct foo
{
foo() : my_bool(), my_int() { }
bool my_bool;
int my_int;
};
As @sbi notes, if you want to manually initialize the struct, even without the default constructor, you can do foo myFoo = foo();
正如@sbi 所指出的,如果您想手动初始化结构,即使没有默认构造函数,您也可以这样做 foo myFoo = foo();
回答by tjm
Have a default constructor:
有一个默认构造函数:
struct foo {
foo() : my_bool(false), my_int(0) {}
bool my_bool;
int my_int;
};
回答by Johannes Schaub - litb
You are not creating anyobject in that code. Initialization is done when you create objects, and is not particularly tucked by the way you declare the struct.
您没有在该代码中创建任何对象。初始化是在您创建对象时完成的,并且不会特别受您声明结构体的方式的影响。
For instance the following initializes the boolean to false
and the integer to 0
例如,以下将布尔值初始化为false
和整数为0
foo f = { };
Notice that you have just typdefedyour struct. You have not created an object. Like others said you can omit the typedef in C++ and just declare the struct, and you are still able to refer to the type by just saying foo
.
请注意,您刚才typdefed你的结构。您尚未创建对象。就像其他人说的那样,您可以在 C++ 中省略 typedef 并仅声明结构体,并且您仍然可以仅通过说foo
.
If you omit explicit initialization when you define an object, then for sure no initialization is done unless the object is defined at namespace scope or defined as static
locally (in which case all members are zero-initialized) or the class has a user defined default constructor that does initialization accordingly.
如果您在定义对象时省略显式初始化,那么肯定不会进行初始化,除非该对象是在命名空间范围内定义的或定义为static
本地的(在这种情况下,所有成员都是零初始化的)或者该类具有用户定义的默认构造函数相应地进行初始化。
回答by M. Williams
As long as you are declaring the structs in a C-way, you could use zeromemory
to null exactly sizeof(foo)
bytes, therefore defaulting all values to 0
.
只要您以 C 方式声明结构,您就可以使用zeromemory
NULL 精确sizeof(foo)
字节,因此将所有值默认为0
.
In C++, you could define your structure with a constructor which would set your values to some default values if needed.
在 C++ 中,您可以使用构造函数定义您的结构,如果需要,该构造函数会将您的值设置为某些默认值。
回答by Donnie
c and c++ don't initialize variables at all. They contain whatever happened to be in the memory location that they're now in previously. This also applies for member variables in classes and structs unless you specifically initialize them to a value.
c 和 c++ 根本不初始化变量。它们包含它们之前所在的内存位置中发生的任何事情。这也适用于类和结构中的成员变量,除非您专门将它们初始化为一个值。