Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to put an std::array<POD, N> in a union?

I have a union declared like that:

union
{
    int all[4];
    struct
    {
        int a, b, c, d;
    };
};

The point of the all array is simply to make iteration over the 4 fields simpler.

To make it even simpler, I'd like to replace it with an std::array<int, 4>. Would that expose me to nasal demons?

like image 419
zneak Avatar asked Feb 13 '14 18:02

zneak


1 Answers

First, it's important to note that merely having two objects of different types in a union is never undefined. What's undefined is to write to one and read from another, with one exception:

[C++11: 9.5/1]: [ Note: One special guarantee is made in order to simplify the use of unions: If a standard-layout union contains several standard-layout structs that share a common initial sequence (9.2), and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members; see 9.2. —end note ] [..]

Now, although it's not written out specifically anywhere that std::array fits this rule, the fact that it's an aggregate with only element members seems enough of a guarantee:

[C++11: 23.3.2.1/2]: An array is an aggregate (8.5.1) that can be initialized with the syntax:

   array<T, N> a = { initializer-list };

where initializer-list is a comma-separated list of up to N elements whose types are convertible to T.

So, it's safe not only to have the union exist in the first place, but also to read and write to either member at will.

Therefore, my conclusion is: yes; it is safe.

like image 176
Lightness Races in Orbit Avatar answered Sep 28 '22 07:09

Lightness Races in Orbit