C++ Logo


Advanced search

Subject: Re: [ub] type punning through congruent base class?
From: Jens Maurer (Jens.Maurer_at_[hidden])
Date: 2014-01-16 15:48:59

On 01/16/2014 09:17 PM, Herb Sutter wrote:
>>>> | struct B { int x; }; // 1
>>>> | void* p = malloc(sizeof(B)); // 2
>>>> | B* pb = static_cast<B*>(p); //3
>>>> | pb->x = 17; // 4
>>>> |
>>>> | I take it as obvious that the lifetime of an object of type B has
>>>> | begun somewhere in this code snippet.

>>>> Well, in fact I don't take it obvious that the lifetime of an object
>>>> has even begun!
>>>> I don't even see that or object has been constructed or initialized.
>>> Agreed. I would expect line 4 to be at least unspecified behavior and
>>> probably undefined behavior.
> OK, let me back this off to just "I would expect that in this code no lifetime of any object has begun."

So, a subsequent read of "pb->x" would then be undefined behavior
according to 3.8p5 bullet 2?

This seems to break C compatibility, since the code above (after replacing
the static_cast) certainly works as expected in C.

I have no objections to someone rewriting 3.8 basic.life to suit feelings
about the intuitive meaning of "lifetime", but let's please have a holistic
approach in a paper.


SG12 list run by herb.sutter at gmail.com