C++ Logo

std-discussion

Advanced search

Re: UB, unions, common initial sequence and constexpr

From: Edward Catmur <ecatmur_at_[hidden]>
Date: Fri, 21 Oct 2022 14:13:11 +0100
On Fri, 21 Oct 2022 at 14:00, Lénárd Szolnoki via Std-Discussion <
std-discussion_at_[hidden]> wrote:

> Hi,
>
> It's explicitly not allowed in constexpr:
>
> https://timsong-cpp.github.io/cppwp/n4868/expr.const#5.9
>

This is annoying, esp. if P2641 is adopted; the compiler knows which member
is active, so it's just busywork for the user to iterate through them to
find the one which is active. Currently:

    constexpr char t1 = __builtin_constant_p(u.a.e0) ? u.a.e0 : u.b.e0;

https://godbolt.org/z/4av4P6Y5n

Cheers,
> Lénárd
>
>
> On 21 October 2022 12:36:57 BST, Wilhelm Meier via Std-Discussion <
> std-discussion_at_[hidden]> wrote:
>>
>> HI all,
>>
>> the standard explicitly makes this exception: accessing an inactive union member is not UB if the members are structs with initial common sequence.
>>
>> Is this also true in a constexpr context? I ask this because the chapter for constexpr expression does not mention this exception accessing an inactive memeber.
>>
>> Here is some test-code:
>>
>> struct A {
>> char e0;
>> };
>> struct B {
>> char e0;
>> };
>>
>> template<typename A, typename B>
>> union U {
>> A a;
>> B b;
>> };
>>
>> int main() {
>> constexpr U<A, B> u{.a = {1}}; // sets member a active
>> constexpr char t1 = u.b.e0; // should be ok, because read via a struct with common initial sequence, but also in a constexpr context?
>> }
>> --
>> Wilhelm
>>
>> --
> Std-Discussion mailing list
> Std-Discussion_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion
>

Received on 2022-10-21 13:13:24