Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail
From: Tim Rentsch
Newsgroups: comp.lang.c++
Subject: Re: Union type punning in C++
Date: Sat, 11 Jan 2020 07:10:29 -0800
Organization: A noiseless patient Spider
Lines: 46
Message-ID: <86d0bq2fmi.fsf@linuxsc.com>
References: <490dd5d6-fb8a-482b-a88d-550b8a4defd0@googlegroups.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Injection-Info: reader02.eternal-september.org; posting-host="a658bb27d1b88b897660621da5fe7a9e"; logging-data="26471"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19qAycHJNAcP68sQ6shDnK2PSFZi0HP1vE="
User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Cancel-Lock: sha1:anQbAqTmBjoqS8jkVpLD1KsyJNY= sha1:JwzSzZWKAu/I/h4bglJ9vJkUluw=
Xref: csiph.com comp.lang.c++:71290
Tiib writes:
> On Friday, 3 January 2020 01:39:54 UTC+2, Chris M. Thomasson wrote:
>
>> On 1/1/2020 11:24 AM, Mr Flibble wrote:
>>
>>> Undefined behaviour aside is C++ union type punning an acceptable hack
>>> or not, given that it is legal in C?
>>> If it works on all the compilers I care about does it really matter that
>>> it is *currently* classed as undefined behaviour?
>>> I would say that everyone has "secretly" fucking done it some time or
>>> other so the C++ Standards Committee should get there act together and
>>> legalize it like it has been in C.
>>> Can anyone provide a straight answer to this?
>>
>> Is there some cryptic hidden thing in the standard that just might
>> "allow" for the following code to run without ub?
>
> Possibly.
>
>> ___________________________
>> #include
>>
>> struct base
>> {
>> int p0;
>> };
>
> Standard layout classes have lot of additional guarantees.
>
>> struct object_0
>> {
>> base b;
>> int p0;
>> };
>
> Standard layout with common initial sequence with base.
Unless I'm missing something the two struct types base and object_0
don't have a common initial sequence (or we might say the common
initial sequence is the empty set). The first member of base is of
type int. The first member of object_0 is of type base. These two
types, int and base, are not layout-compatible: they are not the
same type; they are not layout-compatible enumerations; and they
are not layout-compatible standard-layout class types. Hence there
is no common initial sequence.