C++ Logo


Advanced search

Re: Accessing an object with a char pointer.

From: yo mizu <mizu2594_at_[hidden]>
Date: Fri, 15 May 2020 20:33:02 +0900
On Thu, May 14, 2020 at 12:50 AM Christopher Hallock via
Std-Discussion <std-discussion_at_[hidden]> wrote:
>> So is the behavior of the other example below defined?
>> int c = 4;
>> char d = *reinterpret_cast<char*>(&c);
>> The result of the lvalue-to-rvalue conversion would be the value of
>> the int object (4).
>> It is not an object of char, but the value of 4 can be represented by char.
>> If this behavior is defined, and the value of "d" is 4, I think it is
>> at odds with the behavior of many existing compilers for big endian
>> architectures.
> I agree that the Standard makes this example well-defined but, accidentally, with nonsense semantics.
>> And how about the following example.
>> struct E {} e {};
>> char f = *reinterpret_cast<char*>(&e);
>> Is the behavior of this example defined?
>> If this is undefined behavior, what description in the standard is it based on?
> I think the lvalue-to-rvalue conversion and/or the aliasing provision of [basic.lval]/11 is underspecified in this case, but it's kind of moot because we want the Standard to say that reinterpret_cast<char*>(...) simply points to the first byte to begin with.

Thank you for your answer!

Your response shows me that there seem to be a lot of problems with
accessing an object with a char pointer.

In what situations would the above rule be useful?
According to P1839, pointers obtained by reinterpret_cast<char*>(...)
cannot be addable nor incrementable.
If it is not useful, I think the Standard should remove the sentence
[basic.lval] (11.3) after P1839 is merged.

Best regards,
Yo Mizu

Received on 2020-05-15 06:36:17