C++ Logo

sg12

Advanced search

Re: [ub] type punning through congruent base class?

From: David Vandevoorde <daveed_at_[hidden]>
Date: Thu, 16 Jan 2014 15:24:17 -0500
On Jan 16, 2014, at 3:17 PM, Herb Sutter <hsutter_at_[hidden]> wrote:
[...]
> As I pointed out in other email that might have been delayed by moderation, if in the above code any lifetime began, then we have a contradiction in the standard because we would be in the untenable position that two objects can have the same address:
>
> struct B { int x };
> void* p = malloc(sizeof(B));
>
> B* pb = (B*)p;
> pb->x = 17;
>
> short* ps = (short*)p
> *ps = 17;
>
> None of this code can be viewed as starting a lifetime. Otherwise, proof by contradiction (meaning contradiction in the standard): B and short are both trivially-constructible. If any of these lines start a lifetime of either a B or a short on the grounds that they are trivially-constructible, then this code must start the life of *both* a B and a short, and then *pb and *ps have the same address, which is a contradiction. Therefore none of these lines start a lifetime, QED.
>
> Am I missing something?

I think so: 3.8/1 also says that the lifetime of an object ends if its storage is reused. So when you write to *ps, you've terminated the lifetime of *pb.

        Daveed

Received on 2014-01-16 21:24:22