The C++ standard says that accessing a non-active union member is UB.
But it states an exception from this rule for structs with a common-initial-sequence.
The following is such an example:
template<typename T>
struct A {
T e0;
T e1;
T e2;
};
template<typename T>
struct B {
T e0;
T e1;
T e2;
};
template<typename T>
union AB {
A<T> a;
B<T> b;
};
template<typename T>
constexpr char test() {
AB<T> ab;
ab.a.e0 = 1;
return ab.b.e0;
}
int main() {
constexpr auto t1 = test<char>();
}
UB is not allowed in constexpr-contexts, but the call to test()
in main()
results in an error at least for gcc. Why is this UB, although the C++ standard states the exception for this?
The error (g++) is:
In function 'int main()': bm62.cc:107:35: in 'constexpr' expansion of 'test()' bm62.cc:107:36: error: accessing 'AB::b' member instead of initialized 'AB::a' member in constant expression 107 | constexpr auto t1 = test();