Q:

How to zero-initialize an union?

Consider the following code:
struct T {
    int a;
    union {
        struct {
            int a;
        } s1;
        struct {
            char b[1024];
        } s2;
    };
};

int main() {
    T x = T();
}

Since an explicit constructor is called, the above code ends-up zero-initializing all the data members in x.
But I would like to have x zero-initialized even if an explicit is not called. To do that one idea would be to initialize the data members in their declaration, which seems to be okay for T::a. But how can I zero-initialize all the memory occupied by the union by using
the same criteria?
struct T {
    int a = 0;
    union {
        struct {
            int a;
        } s1;
        struct {
            char b[1024];
        } s2;
    };
};

int main() {
    T x; // I want x to be zero-initialized
}

A:

You could zeroize using memset:
memset(&x, 0, sizeof(x));

A:

For a union without a user-defined default constructor, value initialization is zero initialization.
However, zero-initialization of a union may not zero all memory, but only the padding and the first member.  If the first member isn't the largest, you could be left with non-zero content.
Since you know that s2 is largest, you can make a default constructor that zeros it:
struct T
{
    int a;
    union {
        int s1a;
        char s2b[1024];
    };
    T() : a(), s2b() {}
};

And now
T x;

will be zeroed.

