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?
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 toT
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With