Any useful difference between std::bit_cast and std::start_lifetime_as?

4.1k Views Asked by At

std::bit_cast is apparently being introduced in c++20. and std::start_lifetime_as is proposed for c++23 (from P0593R5). As they appear to both require that the datatypes involved be trivial anyways, will there be any need for the former once the latter is introduced?

Apologies in advance for not providing any more information about these new features. I only just heard about them after watching a cppcon 2019 lecture on type-punning, and I wasn't able to find much about start_lifetime_as with google. I'm hoping someone else who sees this might know more.

2

There are 2 best solutions below

4
Davis Herring On BEST ANSWER

The answer is trivial: bit_cast returns a value, whereas start_lifetime_as “alters” memory (in a way that exists in the abstract machine but is not expected to affect any physical bits). You use the former to (once) interpret an existing object as a set of bits; you use the latter to (permanently) interpret existing bits as an object.

1
Parker Coates On

std::bit_cast copies the bits of its argument to a new value of a different type.

float myFloat = 3.14;
auto asUint = std::bit_cast<uint32_t>(myFloat);
auto asBytes = std::bit_cast<std::array<char,4>>(myFloat);

myFloat, asUint and asBytes are separate variables with separate addresses. The compiler may be able to optimise some them away completely, but logically they are completely distinct values that just happen to have the same size and bits.

std::start_lifetime_as doesn't do anything. It just informs the compiler that it can treat a range of memory as if it contained an array of the specified type. This then allows the developer to use that memory as an array without triggering undefined behaviour. It doesn't physically modify the memory passed to it and it doesn't return anything. It's purely for C++ object model bookkeeping.

Edit: Robert Leahy has an excellent presentation explaining the problems these functions were created to solve and how they are implemented.