1

Does this design pattern have a name? I wanted to read more about it but I don't really know what to google for.

Minimal example:

#include <iostream>

struct Color {
    Color() {}

    union {
        uint32_t rgba;
        struct {
            uint8_t r, g, b, a;
        };
    };

    void print() {
        std::cout << std::hex << "RGBA(" << (int)r << ", " << (int)g << ", " << (int)b << ", " << (int)a << ")\t(" << rgba << ")\n";
    }
};

int main(int argc, char* argv[]) {
    Color A, B;
    A.print();
    A.a = 0xff;
    A.g = 0xaa;
    A.print();
    A.rgba = 0x116699aa;
    A.print();
    system("pause");
}

Output:

RGBA(0, 0, 0, 0)        (0)
RGBA(0, aa, 0, ff)      (ff00aa00)
RGBA(aa, 99, 66, 11)    (116699aa)
Eris
  • 35
  • 3
  • No, I'm afraid that there is no Buzzword Bingo for this. – Sam Varshavchik Aug 01 '22 at 11:04
  • Maybe *nested* structure/union? – Adrian Mole Aug 01 '22 at 11:09
  • 3
    BTW: Access a non active union member is UB in C++! See also: https://stackoverflow.com/questions/11373203/accessing-inactive-union-member-and-undefined-behavior Yes we know, it works on all known compilers ... but it is against the rules! – Klaus Aug 01 '22 at 11:14
  • @Klaus gcc guarantees it works, and by extension probably clang too. – Passer By Aug 01 '22 at 11:16
  • 3
    It's called **type punning** through a union. The C++ standard declares it to be **undefined behavior**. The **GCC** compiler has compiler extension to support type punning through a union with C++. LLVM (clang) behavior for strict-aliasing is not the same as GCC (g++) behavior; I've not been able to confirm that LLVM has the same compiler extension for type punning through a union as GCC. – Eljay Aug 01 '22 at 11:25
  • 1
    Interesting that the question was closed :-) The question did not ask if access is allowed or not... the given link is only related to the example code but not to the question... more to say? – Klaus Aug 01 '22 at 11:26
  • @Klaus A mistake is a mistake, doesn't matter if it was intentional(or not)! – Jason Aug 01 '22 at 11:29
  • using compiler extensions isnt a mistake when done intentionally – 463035818_is_not_an_ai Aug 01 '22 at 11:40
  • It’s referred to as ‘do not use’ or ‘UB’. At minimum till c++17 it’s undefined behaviour, i.e., anything might happen (not only any value - anything). On ItaniumABI, it’s well-defined and works. – lorro Aug 01 '22 at 11:46

0 Answers0