C++ Logo

SG12

Advanced search

Subject: Re: [ub] type punning through congruent base class?
From: Herb Sutter (hsutter_at_[hidden])
Date: 2014-01-16 13:44:25


> | 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. Now the question is: which
> | specific line begins that lifetime? As you say, casting a pointer
> | doesn't begin or end a lifetime; I think we can rule out line 3 as the
> | one that begins the lifetime of that B object. Line 1 doesn't look too
> promising either.
>
> 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.


> I think we should go back to the general principle - which works well for
> general objects - that an object lifetime starts right after its construct finishes
> and ends right before its destructor starts. I don't think we want to
> compromise that.

Exactly, this is essential. It seems the confusion is about whether we say this clearly for trivially-constructible types. If we don't, we should.

Herb



SG12 list run by herb.sutter at gmail.com