C++ Logo

sg12

Advanced search

Re: [ub] Type punning to avoid copying

From: Gabriel Dos Reis <gdr_at_[hidden]>
Date: Thu, 25 Jul 2013 17:31:23 -0500
Lawrence Crowl <Lawrence_at_[hidden]> writes:

| On 7/25/13, Gabriel Dos Reis <gdr_at_[hidden]> wrote:
| > Lawrence Crowl <Lawrence_at_[hidden]> writes:
| >
| > | On 7/25/13, Gabriel Dos Reis <gdr_at_[hidden]> wrote:
| > | > Lawrence Crowl <Lawrence_at_[hidden]> writes:
| > | >
| > | > | On 7/25/13, Howard Hinnant <howard.hinnant_at_[hidden]> wrote:
| > | > | > It was this SO question that started this thread:
| > | > | >
| > | > | > http://stackoverflow.com/q/17789928/576911
| > | > | >
| > | > | > I'm curious: The accepted answer uses memcpy and the claim is that
| > this
| > | > is
| > | > | > a correct answer to the question. That is it does not exhibit
| > | > undefined
| > | > | > behavior. My current understanding is that I agree with this
| > answer.
| > | > But I
| > | > | > wanted to check here. Do people here agree that:
| > | > | >
| > | > | > http://stackoverflow.com/a/17790026/576911
| > | > | >
| > | > | > does not break the aliasing rules, or otherwise invoke undefined
| > | > behavior?
| > | > |
| > | > | I believe so.
| > | >
| > | > I can't find the rule (in the standards) that the memcpy() into i
| > | > constitutes an initialization.
| > |
| > | It is trivial assignment, and initialization is unnecessary because it
| > | is trivial. We could probably be clearer.
| >
| > I can't find the rule for that interpretation. The closest I can come
| > to is 3.9/3, but that paragraph requires copying from an object of the
| > same type:
| >
| > # For any trivially copyable type T, if two pointers to T point to
| > # distinct T objects obj1 and obj2, where neither obj1 nor obj2 is a
| > # base-class subobject, if the underlying bytes (1.7) making up obj1 are
| > # copied into obj2,41 obj2 shall subsequently hold the same value as
| > obj1.
| >
| > | > One also needs something for the
| > | > memcpy() back into x, saying that does not yield a trap representation,
| > | > which would otherwise lead to undefined behaviour in the update:
| > | >
| > | > x = x*(1.5f - xhalf*x*x);
| > |
| > | But at that point aren't we already platform dependent?
| > | I.e. dealing with the representation?
| >
| > I can't find rules that cover that, or that would make it platform
| > dependent.
|
| I was trying to get a sound intuition. Once we have that, I think we
| can make the necessary wording.

OK. Though I would prefer it to end the lifetime of the previous object
and start a new one -- but that isn't a strong preference; the first
thing is to get it defined.

-- Gaby


|
|
| --
| Lawrence Crowl

Received on 2013-07-26 00:31:38