Is the use of union in this matrix class completely safe?

Posted by identitycrisisuk on Stack Overflow See other posts from Stack Overflow or by identitycrisisuk
Published on 2010-05-21T09:58:37Z Indexed on 2010/05/21 10:00 UTC
Read the original article Hit count: 176

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about c++

Related posts about union