Is using a union in this matrix class completely safe?

Unions are not something I often used, and looking at a few other questions on them, it seems that there is almost always some kind of warning where they may not work. For instance. structures possibly having unexpected additions or finite differences.

It looks like this in the math library I use, although I wondered if this is an absolutely safe use. I assume that multidimensional arrays do not have an extra complement, and since the type is the same for both definitions, are they guaranteed to occupy exactly the same amount of memory?

template<typename T> class Matrix44T
{
    ...

    union
    {
        T M[16];
        T m[4][4];
    } m;
};

Are there any flaws in this setting? Will the order of definition make any difference to how this works?

+3
3

Matrix, , , :

9.5.1:

, . [: : POD-union POD-, (9.2), POD- type POD-, POD- ; . 9.2. ]

: do m m , 9.2/15:

POD-union ( 9): , , ( ) (3.9).

, , , m m .

, .

+4

, .

union { int a; float b; } wrong;

wrong.a = 1;
printf("%f", wrong.b);

, "a", , "a", undefined.

: . , , .

+1

No. This seems to be just good use unionaccording to your assumptions.

I would choose the best names, not mand m, but other than that, it's a nice use for union.

0
source

Source: https://habr.com/ru/post/1746538/


All Articles