如何在C ++中将结构初始化为0 [英] How to initialize a struct to 0 in C++

查看:130
本文介绍了如何在C ++中将结构初始化为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个相关的C答案,在C ++上不起作用(作为结构的零初始值设定项):将结构初始化为0 。提出的解决方案之一是:

Here is a related C answer that doesn't work (as a zero initializer for a struct) on C++: Initializing a struct to 0. One of the solutions presented is this:

myStruct _m1 = {0}; 

这在C语言中效果很好,但在C ++中不起作用。 :(:

This works fine in C, but it doesn't work in C++. :( :


错误:无法初始化类型为'int'`的右值'myScope :: MyStruct'的成员子对象。

error: cannot initialize a member subobject of type 'myScope::MyStruct' with an rvalue of type 'int'`.

如何在C ++中将结构零初始化?

How do you zero-initialize a struct in C++?


  1. 在C中将
    a结构初始化为0:将结构初始化为0

  2. 更新:(一个相邻但不重复的问题,它也非常有用)使用空花括号的初始化

  1. Initializing a struct to 0 in C: Initializing a struct to 0
  2. Update: (an adjacent, but NOT duplicate question which also turns out to be very useful) Initialization with empty curly braces



投票给mods来结束这个问题的人



我的问题不是这个问题的重复(使用空花括号的初始化),因为另一个问题不是在问关于用C ++初始化结构的各种方法以及C方法为什么不起作用的原因,他们问的是为什么C ++关键字 explicit 破坏了其中一个?他们的初始化技术。两个不同的问题。不是重复的。

To the mods voting to close this question:

My question is not a duplicate of this other question (Initialization with empty curly braces), as this other question isn't asking about the various ways to initialize a struct in C++ and why the C way doesn't work, rather, they are asking why does the C++ keyword explicit break one of their initialization techniques. Two distinct questions. Not duplicate.

推荐答案

我知道了:要使其编译,只需删除零即可:

I figured it out: to get it to compile, just delete the zero:

myStruct _m1 = {};

现在可以编译了。但是,我进行了一堆测试来检查一些东西 ,并且这不会将结构的所有元素初始化为零!相反,它将结构初始化为默认值。

It now compiles. However, I ran a bunch of tests to check some things, and this does NOT initialize all elements of the struct to zero! Rather, it initializes the struct to its default values.

假定您具有以下结构:

typedef struct
{
    int num1 = 100;
    int num2 = -100;
    int num3;
    int num4 = 150;
} data_t;

注意:上面的 typedef 是从我在C中而不是C ++中测试此东西时得到的结果(当然,尽管C中不允许使用默认结构值)。对于C ++,它是首选:

Note: the typedef above is a carry-over from when I was testing this stuff in C instead of C++ (although the default struct values are not allowed in C, of course). For C++, this is preferred instead:

struct data_t
{
    int num1 = 100;
    int num2 = -100;
    int num3;
    int num4 = 150;
};

所以无论我在什么地方不必要地使用 typedef 来定义下面的结构。

So please ignore it wherever I unnecessarily use typedef to define the structs below.

无论如何,如果我声明上述 data_t 结构,然后执行以下操作:

Anyway, if I declare one of the above data_t structs, and then do this:

data_t d2 = {};
printf("d2.num1 = %i\nd2.num2 = %i\nd2.num3 = %i\nd2.num4 = %i\n\n",
       d2.num1, d2.num2, d2.num3, d2.num4);

...输出将是:

d2.num1 = 100
d2.num2 = -100
d2.num3 = 0
d2.num4 = 150

我什至不确定 d2.num3 是否为零,因为它被初始化为零或由于未初始化而导致该内存位置恰好包含零。

And I'm not even sure if d2.num3 is zero because it was initialized to zero or because it was left uninitialized, and that memory location happened to contain zero.

如此处所述: https://en.cppreference.com/w/cpp/language/zero_initialization ,您也可以执行以下操作:

As explained here: https://en.cppreference.com/w/cpp/language/zero_initialization, you can also do this:

myStruct _m1{};

在上面的示例中,此代码:

In the example above, this code:

data_t d2{};
printf("d2.num1 = %i\nd2.num2 = %i\nd2.num3 = %i\nd2.num4 = %i\n\n",
       d2.num1, d2.num2, d2.num3, d2.num4);

...将产生与上面显示的输出相同的输出。

...would produce output identical to what I showed above.

即使在将结构设置为 = {0} 的情况下也可以正常工作,例如:

Even in cases where setting the struct to = {0} DOES work, such as this:

// Does NOT do what I expected! Only sets the FIRST value in the struct to zero! 
// The rest seem to use default values.
data_t d3 = {0};
printf("d3.num1 = %i\nd3.num2 = %i\nd3.num3 = %i\nd3.num4 = %i\n\n",
       d3.num1, d3.num2, d3.num3, d3.num4);

...输出仍然不是我期望的,因为它只设置了 值为零! (我不明白为什么):

...the output is still not what I expected, as it only sets the first value to zero! (I don't understand why):

d3.num1 = 0
d3.num2 = -100
d3.num3 = 0
d3.num4 = 150

在C样式数组,但是(不是结构),这些语义可以正常工作。请在此处参考此答案(如何将数组的所有成员初始化为相同的值?)。因此,以下各行均在使用C ++时将C样式数组的所有元素都设置为零:

On C-style arrays, however (NOT structs), these semantics work fine. Refer to this answer here (How to initialize all members of an array to the same value?). The following lines, therefore, both set all elements of the C-style array to zero when using C++:

uint8_t buffer[100] = {0}; // sets all elements to 0 in C OR C++
uint8_t buffer[100] = {};  // sets all elements to 0 in C++ only (won't compile in C)

因此,经过大量实验,它看起来像以下几个方法是将结构PERIOD初始化为零的唯一方法。如果您有不同的认识,请在这里评论和/或留下您自己的答案。

So, after much experimentation, it looks like the following several ways are the ONLY ways to zero-initialize a struct, PERIOD. If you know differently, please comment and/or leave your own answer here.


  1. 要明确:

  1. Be explicit:

// C-style typedef'ed struct
typedef struct
{
    int num1 = 100;
    int num2 = -100;
    int num3;
    int num4 = 150;
} data_t;

// EXPLICITLY set every value to what you want!
data_t d1 = {0, 0, 0, 0};
// OR (using gcc or C++20 only)
data_t d2 = {.num1 = 0, .num2 = 0, .num3 = 0, .num4 = 0}


  • 使用 memset()将所有字节强制为零:

  • Use memset() to force all bytes to zero:

    data_t d3;
    memset(&d3, 0, sizeof(d3));
    


  • 首先将所有默认值设置为零:

  • Set all default values to zero in the first place:

    // C-style typedef'ed struct
    typedef struct
    {
        int num1 = 0;
        int num2 = 0;
        int num3 = 0;
        int num4 = 0;
    } data_t;
    
    // Set all values to their defaults, which are zero in
    // this case
    data_t d4 = {};
    // OR
    data_t d5{}; // same thing as above in C++
    
    // Set the FIRST value only to zero, and all the rest
    // to their defaults, which are also zero in this case
    data_t d6 = {0};
    


  • 为C ++结构编写一个构造函数

  • Write a constructor for the C++ struct

    // 1. Using an initializer list
    struct data
    {
        int num1;
        int num2;
        int num3;
        int num4;
    
        data() : 
            num1(0),
            num2(0),
            num3(0),
            num4(0) {}
    };
    
    data d7; // all values are zero
    
    // OR: 2. manually setting the values inside the constructor
    struct data
    {
        int num1;
        int num2;
        int num3;
        int num4;
    
        data()
        {
            num1 = 0;
            num2 = 0;
            num3 = 0;
            num4 = 0;
        }
    };
    
    data d8; // all values are zero
    


  • 使用没有默认值的结构,并创建对象您可以从中创建静态

    tpedef struct
    {
        int num1;
        int num2;
        int num3;
        int num4;
    } data_t;
    
    // `static` forces a default initialization of zero for each
    // value when no other default values are set
    static data_t d9;
    


  • 因此,如果您的结构体中非零默认值,并且您想将所有值归零,则必须明确执行!这里有一些其他方法:

  • So, if you have a struct with non-zero default values, and you want to zero all values, you must do it EXPLICITLY! Here are some more ways:

    // 1. Have a `constexpr` copy of the struct that you use to
    // reset other struct objects. Ex:
    
    struct data
    {
        int num1 = 1;
        int num2 = 7;
        int num3 = -10;
        int num4 = 55;
    };
    
    constexpr data DATA_ALL_ZEROS = {0, 0, 0, 0};
    
    // Now initialize d13 to all zeros using the above `constexpr` struct 
    // object
    data d13 = DATA_ALL_ZEROS; 
    
    
    // OR 2. Use a `zero()` member function to zero the values:
    
    struct data
    {
        int num1 = 1;
        int num2 = 7;
        int num3 = -10;
        int num4 = 55;
    
        zero()
        {
            num1 = 0;
            num2 = 0;
            num3 = 0;
            num4 = 0;
        }
    };
    
    data d14;
    d14.zero();
    




  • 这里最大的收获是没有其中: data_t d {} data_t d = {} data_t d = {0} ,实际上将结构的所有成员设置为零!



    The big take-away here is that NONE of these: data_t d{}, data_t d = {}, and data_t d = {0}, actually set all members of a struct to zero!


    1. data_t d {} 将所有值设置为在结构中定义的默认值。

    2. data_t d = {} 还将所有值都设置为其默认值。

    3. data_t d = {0} 仅将FIRST值设置为零,并将所有其他值设置为默认值。值设置为默认值。

    1. data_t d{} sets all values to their defaults defined in the struct.
    2. data_t d = {} also sets all values to their defaults.
    3. And data_t d = {0} sets only the FIRST value to zero, and all other values to their defaults.

    所以,要明确

    请注意,我写的上述主要内容似乎与此文档矛盾,因此它使我提出了一个后续问题,列在下面的参考文献#1中,事实证明对我的理解非常有帮助!

    Note that the above key take-aways I wrote seem to contradict this documentation, so it has led me to ask this follow-up question, listed as Reference #1 below, which has proven VERY helpful to my understanding!


    1. [最有用的] 为什么不将C ++结构初始化为`= {0}`将其所有成员都设置为0?

    2. [非常有用]

    1. [MOST USEFUL] Why doesn't initializing a C++ struct to `= {0}` set all of its members to 0?
    2. [VERY USEFUL]

    1. https:/ /en.cppreference.com/w/cpp/language/zero_initialization

    2. https://en.cppreference.com/w/cpp/language/aggregate_initialization

    3. https://en.cppreference.com/w/cpp/language/value_initialization

    1. https://en.cppreference.com/w/cpp/language/zero_initialization
    2. https://en.cppreference.com/w/cpp/language/aggregate_initialization
    3. https://en.cppreference.com/w/cpp/language/value_initialization


  • [非常有用]将数组(不是结构)的所有成员初始化为相同的值:

  • [VERY USEFUL] Initializing all members of an array (not struct) to the same value:


    1. 如何将数组的所有成员初始化为相同值?

    2. [仅适用于gcc] 如何将数组的所有成员初始化为相同的值?

    1. How to initialize all members of an array to the same value?
    2. [gcc only] How to initialize all members of an array to the same value?


  • https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world /blob/master/cpp/struct_initialization.cpp

  • https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world/blob/master/cpp/struct_initialization.cpp


    1. 克隆此存储库并使用 cpp / run_struct_initialization自己运行代码.sh

    1. Clone this repo and run the code yourself with cpp/run_struct_initialization.sh




  • 相关:



    Related:


    1. 初始化默认值结构中的值

    1. Initializing default values in a struct

    这篇关于如何在C ++中将结构初始化为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆