C++ Logo

std-discussion

Advanced search

Re: reading values as bytes without memcpu, from enum unsigned char?

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Wed, 5 Aug 2020 21:47:21 -0400
On Wed, Aug 5, 2020 at 1:58 AM Roman Babinicz via Std-Discussion
<std-discussion_at_[hidden]> wrote:
>
>
> enum class mybyte : unsigned char{};
> using T1 = mybyte;
> auto ptr = new T1 [100];
> *(ptr+10) = static_cast<T1>(50);
> delete []ptr;
>
> Is this well formed way of accessing object via glvalue pointer
> (as in basic.lval#11.3) ?
>
> Because for some other types T1, e.g. for int, one possible reading of
> standard is that this is UB and you need to memcpy the buffer into a new
> location first (and even more likelly needed for non-fundamental types
> in T1).

I don't understand what exactly would be ill-formed about this. So
long as `T1` is a type which is default constructible and `T1` can be
constructed from the integer literal 50, this code is fine. At no
point are you reading any values as bytes. The fact that `unsigned
char` is involved is essentially irrelevant.

ptr is a pointer to an array of 100 `T1`s. So adding `10` to `ptr` is
well-defined; it points to the 10th element (zero-based) of the array.
`ptr + 10` is a valid pointer, and it is a pointer of that points to
the type `T1`. It is also a pointer to an object of type `T1`. `T1` is
the dynamic type of the object being pointed to, so [basic.lval/11.1]
is satisfied.

There is no "reading values as bytes" happening here.

Received on 2020-08-05 20:50:50