C++ Logo

sg12

Advanced search

Re: [ub] Type punning to avoid copying

From: Jeffrey Yasskin <jyasskin_at_[hidden]>
Date: Fri, 26 Jul 2013 11:35:18 -0700
On Fri, Jul 26, 2013 at 9:23 AM, Gabriel Dos Reis <gdr_at_[hidden]> wrote:
> Jeffrey Yasskin <jyasskin_at_[hidden]> writes:
>
> | On Fri, Jul 26, 2013 at 9:10 AM, Gabriel Dos Reis <gdr_at_[hidden]> wrote:
> | > Jeffrey Yasskin <jyasskin_at_[hidden]> writes:
> | >
> | > | On Fri, Jul 26, 2013 at 8:30 AM, Gabriel Dos Reis <gdr_at_[hidden]> wrote:
> | > | > Ion Gaztañaga <igaztanaga_at_[hidden]> writes:
> | > | >
> | > | > [...]
> | > | >
> | > | > | ¿How can we tell the compiler that a memory buffer is really a different
> | > | > | type?
> | > | >
> | > | > Invoke a constructor to turn the raw memory into an object of the
> | > | > desired type.
> | > |
> | > | Can you point to the wording that explains the behavior in that case?
> | >
> | > I am not sure I understand your request. Ion wants to state a region of
> | > storage is of a given type. The behavior after the contructor ran is
> | > what you get after running a constructor -- see section 12.1.
> |
> | Yeah, sorry. I mean, if I write:
> |
> | float f = 3.2f;
> | int* i = new(&f) int;
> | use(*i);
> |
> | where does it say what the value of '*i' is? I'm expecting
> | implementation-defined, but I don't know exactly where to look.
> |
> | Thanks,
> | Jeffrey
>
> The object at 'i' is constructed but not initialized, so its value is
> indeterminate. See 5.3.4/15.

(Or C++14 5.3.4/17, I think)

Ah, that's too bad because it doesn't serve the purpose Ion was asking
about. He wanted a memory buffer with known contents to become the
object representation of an object of a particular type. If the object
post-construction has an indeterminate object representation instead,
he can't use a constructor to turn the raw memory into an object with
the desired value.

Howard, if Gaby's right that new(&memory) int; leaves the object with
indeterminate value even if 'memory' started with a defined value (and
I think he is), then that's the rule you're breaking when you
explicitly change the active member of your union and then read the
new member.

Received on 2013-07-26 20:35:39