C++ Logo

SG12

Advanced search

Subject: Re: [ub] type punning through congruent base class?
From: David Vandevoorde (daveed_at_[hidden])
Date: 2014-01-16 14:24:17


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


SG12 list run by herb.sutter at gmail.com