Unions aren’t something I’ve used that often and after looking at a few other questions on them here it seems like there is almost always some kind of caveat where they might not work. Eg. structs possibly having unexpected padding or endian differences.
Came across this in a math library I’m using though and I wondered if it is a totally safe usage. I assume that multidimensional arrays don’t have any extra padding and since the type is the same for both definitions they are guaranteed to take up exactly the same amount of memory?
template<typename T> class Matrix44T
{
...
union
{
T M[16];
T m[4][4];
} m;
};
Are there any downsides to this setup? Would the order of definition make any difference to how this works?
Although I do exactly the same in my Matrix-class I think this is implementation dependent, reading the standard to the letter:
Standard 9.5.1:
The question then is do
mandMshare a common initial sequence, to answer this we look at 9.2/15:After reading this the answer seems to be, no
mandMare not layout-compatible in the strict sense of the word.In practice I think this will work fine on all compilers though.