C++ Logo


Advanced search

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

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Fri, 7 Aug 2020 11:16:48 -0400
On Fri, Aug 7, 2020 at 10:06 AM <language.lawyer_at_[hidden]> wrote:
> On 07/08/2020 16:51, Jason McKesson via Std-Discussion wrote:
> > The cast is legal. Accessing the `unsigned char` at that address is
> > legal.
> You can't access `unsigned char` objects, `reinterpret_cast<unsigned char*>(buf)` points to the object of `mybyte` type.

According to [basic.lval]/8.8, I can:

> If a program attempts to access the stored value of an object through a glvalue of other than one of the
following types the behavior is undefined:
> ...
> a char, unsigned char, or std::byte type.

So it doesn't matter what `T1` is; you can access that byte as an
`unsigned char`. And indeed, if you could get a pointer to *any* byte
within `T1`, you can access it as an `unsigned char`.

It's getting a pointer to those bytes that is the problem.

> But accessing an object of `mybyte` type through a glvalue of `unsigned char` type is indeed legal, because an enumeration with a fixed underlying type has the same values as the underlying type.

Actually, that's not true. I mean, it is true that the value
representations are the same, but that doesn't mean you can access
them through different types. [basic.lval] has no special provisions
for an enum and its underlying type. The above is only valid because
`unsigned char` gets special provisions.

Received on 2020-08-07 10:20:23