Union initialization in C++ and C

后端 未结 3 1739
太阳男子
太阳男子 2021-02-12 01:17

I have built a working C library, that uses constants, in header files defined as

typedef struct Y {
  union {
    struct bit_field bits;
    uint8_t raw[4];
  }         


        
3条回答
  •  面向向阳花
    2021-02-12 02:15

    I believe that C++11 allows you to write your own constructor like so:

    union Foo
    {
        X x;
        uint8_t raw[sizeof(X)];
    
        Foo() : raw{} { }
    };
    

    This default-initializes a union of type Foo with active member raw, which has all elements zero-initialized. (Before C++11, there was no way to initialize arrays which are not complete objects.)

提交回复
热议问题