|
|
|
|
|
by gavinray
45 days ago
|
|
I want to point out an implemented feature that people SHOULD be adopting but that I doubt will be picked up: P2590R2, Explicit lifetime management (PR106658)
This is for "std::start_lifetime_as<T>". If you have not heard of this before, it's the non-UB way to type-pun a pointer into a structured type.Nearly all zero-copy code that deals with external I/O buffers looks something like: std::unique_ptr<char[]> buffer = stream->read();
if (buffer[0] == FOO)
processFoo(reinterpret_cast<Foo*>(buffer.get())); // undefined behavior
else
processBar(reinterpret_cast<Bar*>(buffer.get())); // undefined behaviour
With this merged, swap the reinterpret_cast for start_lifetime_as and you're no longer being naughty.https://en.cppreference.com/cpp/memory/start_lifetime_as |
|
The "start_lifetime_as" facility does one additional thing beyond providing a tidy standard name for the memory laundering incantation. Semantically it doesn't touch the memory whereas the no-op memmove intrinsically does. In practice, this makes little difference, since the compiler could see that the memmove was a no-op and optimized accordingly.