Date: Sun, 2 Oct 2022 21:41:56 +0800
An example from P0593R6 <https://wg21.link/P0593R6#practical-examples>:
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?
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?
Received on 2022-10-02 13:42:25