I almost spend 2 days to track down a bug in Higgs that could have been easily catched by the compiler (see bug 13952).
It just shouldn't be possible to compare unions. Right now this compares the memory representation, but this is almost always a bug, because a union might only be partially initialized or the assigned fields might differ.
cat > bug.d << CODE
union Foo
{
ubyte sm;
uint bg;
}
void main()
{
Foo a, b;
a.bg = 12121212;
b.bg = 13131313;
a.sm = 2;
b.sm = 2;
assert(a == b); // shouldn't be allowed
}
CODE
dmd -run bug
Comment #1 by Marco.Leise — 2015-03-22T13:30:39Z
Assuming that you were expecting someone to come up with a counter case, in your case it is an either-or sort of structure and after assigning to sm, bg is invalid. Disallowing comparisons all-together means that any struct using unions needs to have its own opEquals that checks which part of the union is 'active' in each instance and compares them if needed.
There are other uses of unions such as:
union Color
{
uint c;
struct { ubyte r, g, b, a; }
ubyte[4] arr;
}
where different representations of the same data are offered and a comparison of the memory representation is correct.
Having to write a comparison function for every struct that uses a color can become a chore.
Comment #2 by Marco.Leise — 2016-02-10T04:24:29Z
I think when I wrote the above I wasn't aware that unions can have toString(). Can they also offer a custom opEquals() ? That would be more convenient for cases like the color example or float/int "reinterpret cast" named unions which can perform the comparison themselves instead of the one in Higgs that is anonymously embedded in a struct with a tag.
Comment #3 by robert.schadek — 2024-12-13T18:39:48Z