Does this union break strict aliasing? What about floating point registers

前端 未结 2 376
感情败类
感情败类 2021-01-21 14:34
union
{
    Uint32 Integer;
    Float32 Real;
} Field;    

I have to use that union for a little IEEE trick, does that break strict aliasing? GCC is no

2条回答
  •  执笔经年
    2021-01-21 15:19

    Aliasing via a union is defined in C but has undefined behaviour in C++; the undefined behaviour is equivalent to that which occurs when reading from an uninitialized variable (a lvalue-to-rvalue conversion).

    Accordingly, the most likely way this would break is in the optimiser deciding to eliminate the read from the union, as it does not have a defined value. However, most C-and-C++ compilers are likely to give you the C behaviour as they need to support that anyway.

    The safe way to alias the values is via bytewise copy e.g. std::memcpy or std::copy(reinterpret_cast(...), ...). Alternatively, if you can compile your project in both C and C++ you could move the union aliasing code to a C source file and compile just that code as C.

提交回复
热议问题