Date: Sun, 2 Oct 2022 10:23:53 -0400
On Sun, Oct 2, 2022 at 9:42 AM blacktea hamburger via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> An example from P0593R6:
>
> unique_ptr<char[]> Stream::read() {
> // ... determine data size ...
> unique_ptr<char[]> buffer(new char[N]);
> // ... copy data into buffer ...
> return buffer;
> }
>
> void process(Stream *stream) {
> unique_ptr<char[]> buffer = stream->read();
> if (buffer[0] == FOO)
> process_foo(reinterpret_cast<Foo*>(buffer.get())); // #1
> else
> process_bar(reinterpret_cast<Bar*>(buffer.get())); // #2
> }
>
> It's part of the issue IOC is trying to solve. However, it could not solve it, because the implicitly created Foo or Bar object ends the char objects in buffer, as described in #type-punning, the value of it is indeterminate and loading its value results in undefined behavior.
>
> Am I missing something?
`char` is allowed to alias with any object (via [basic.lval]/11). As
such, you're allowed to access the `char` in `buffer[0]` even though a
`Foo/Bar` lives there now. And since you copied data into those bytes,
their value is not indeterminate.
<std-proposals_at_[hidden]> wrote:
>
> An example from P0593R6:
>
> unique_ptr<char[]> Stream::read() {
> // ... determine data size ...
> unique_ptr<char[]> buffer(new char[N]);
> // ... copy data into buffer ...
> return buffer;
> }
>
> void process(Stream *stream) {
> unique_ptr<char[]> buffer = stream->read();
> if (buffer[0] == FOO)
> process_foo(reinterpret_cast<Foo*>(buffer.get())); // #1
> else
> process_bar(reinterpret_cast<Bar*>(buffer.get())); // #2
> }
>
> It's part of the issue IOC is trying to solve. However, it could not solve it, because the implicitly created Foo or Bar object ends the char objects in buffer, as described in #type-punning, the value of it is indeterminate and loading its value results in undefined behavior.
>
> Am I missing something?
`char` is allowed to alias with any object (via [basic.lval]/11). As
such, you're allowed to access the `char` in `buffer[0]` even though a
`Foo/Bar` lives there now. And since you copied data into those bytes,
their value is not indeterminate.
Received on 2022-10-02 14:25:08