C++ Logo

sg12

Advanced search

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

From: Matt Austern <austern_at_[hidden]>
Date: Thu, 16 Jan 2014 14:41:27 -0800
On Thu, Jan 16, 2014 at 2:21 PM, Jens Maurer <Jens.Maurer_at_[hidden]> wrote:

> On 01/16/2014 11:05 PM, Matt Austern wrote:
> > That's an interesting possibility that I hadn't considered. It's
> definitely appealing in some ways, but I think that it, too, would imply
> some pretty big surgery in some pretty fundamental parts of the standard.
> So let's consider the following code snippet:
> > struct MyPOD { int x; }; // 1
> > void* vp = malloc(sizeof(MyPOD)); // 2
> > MyPOD* p1 = static_cast<MyPOD*>(vp); // 3
> > MyPOD* p2 = new MyPOD; // 4
> >
> > So the basic question I'd ask is: after line 4, what are you allowed
> > to do with p1 and what are allowed to do with p2, and how do the
> > answers differ? We've got a couple of choices.
> >
> > First choice: we decide that you aren't allowed to do anything that
> > involves dereferencing p1, since p1 doesn't point to an object.
>
> Please don't confuse "object" with "lifetime".
>
> 1.8p1 says an object is a region of storage. Both *p1 and
> *p2 satisfy that.
>

That's an interesting observation. It's also true, of course, that
  void* vp = malloc(12);
creates a region of storage and thus, by the definition in 1.8p1,
creates an object. I'm a little reluctant to say that this line
creates an object of type T, though, no matter what T is. Maybe
we have subtly different concepts of "object", "object of type T",
and "object whose lifetime has begun". Or maybe we need to
make those subtle distinctions even we aren't currently making
them.


>
> Further, 3.8p1 seems to say that the lifetime of both *p1 and *p2
> has begun.


I agree that 3.8p1 seems to say that. Not everyone seems to
agree that it says that, though; some people also seem to think
that even if it does say that, it shouldn't. I sympathize. That
reading of 3.8p1 has some surprising consequences. (But every
proposed alternative I can think of seems to have some
surprising consequences too.)

                                 --Matt

Received on 2014-01-16 23:41:29