C++ Logo

std-discussion

Advanced search

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

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Fri, 7 Aug 2020 09:51:56 -0400
On Thu, Aug 6, 2020 at 7:12 PM Roman Babinicz via Std-Discussion
<std-discussion_at_[hidden]> wrote:
>
>
>
> On 06/08/2020 03:47, Jason McKesson via Std-Discussion wrote:
> > 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
>
> Thanks, and now for following example (this is the issue I should has
> posted first)
>
> enum class mybyte : unsigned char{};
> using T1 = mybyte;
> auto buf = new T1 [100];
> unsigned char * ptr = reinterpret_cast< unsigned char * > ( buf ) ;
> *(ptr+10) = 50;
> delete []buf;
>
>
> so nowe we access enum objects via the unsigned char (pointer) that
> happens to be the underlying type, but is that enough to avoid need for
> memcpy?

The part here that is undefined behavior is the pointer increment.
Without P1839, there is no array of `unsigned char` to iterate
through. And pointer arithmetic is based on arrays of objects.

The cast is legal. Accessing the `unsigned char` at that address is
legal. But without P1839, actually doing the pointer arithmetic needed
to access more than one such byte is not. It doesn't matter what the
initial type is.

Received on 2020-08-07 08:55:30