Purpose of Unions in C and C++

后端 未结 16 1927
予麋鹿
予麋鹿 2020-11-22 06:55

I have used unions earlier comfortably; today I was alarmed when I read this post and came to know that this code

union ARGB
{
    uint32_t colour;

    str         


        
16条回答
  •  粉色の甜心
    2020-11-22 07:34

    @bobobobo code is correct as @Joshua pointed out (sadly I'm not allowed to add comments, so doing it here, IMO bad decision to disallow it in first place):

    https://en.cppreference.com/w/cpp/language/data_members#Standard_layout tells that it is fine to do so, at least since C++14

    In a standard-layout union with an active member of non-union class type T1, it is permitted to read a non-static data member m of another union member of non-union class type T2 provided m is part of the common initial sequence of T1 and T2 (except that reading a volatile member through non-volatile glvalue is undefined).

    since in the current case T1 and T2 donate the same type anyway.

提交回复
热议问题