std::start_lifetime_as ends the lifetime of its parameter, right? So I can't apply std::start_lifetime_as multiple time to the same pointer, right? So I implemented function lifetimeBits with an intermediate storage as follows:
#include
#include
#include
#include
#include
#include
#include
#include
using DoubleParts = std::tuple;
DoubleParts lifetimeBits(const double value) noexcept
{
static_assert(
sizeof(double)
== sizeof(std::uint16_t) + sizeof(std::uint16_t) + sizeof(std::uint32_t));
// Copy the object representation into aligned byte storage. The byte array
// provides storage for the three implicit-lifetime integer objects.
alignas(std::uint32_t) auto storage =
std::bit_cast>(value);
// Start three independent object lifetimes in non-overlapping regions.
const auto* first =
std::start_lifetime_as(storage.data());
const auto* second =
std::start_lifetime_as(storage.data() + sizeof(std::uint16_t));
const auto* third =
std::start_lifetime_as(
storage.data() + sizeof(std::uint16_t) + sizeof(std::uint16_t));
// Copy the values into the tuple before the local storage is destroyed.
return {*first, *second, *third};
}
int main()
{
constexpr double value = 1.0;
const auto [first, second, third] = lifetimeBits(value);
// The values reflect the platform's byte order. They are not numeric
// conversions from double to integer types.
std::cout << std::hex
<< "first: 0x" << first << '\n'
<< "second: 0x" << second << '\n'
<< "third: 0x" << third << '\n';
}
The first question is why std::start_lifetime_as does not end storage.data(), because it is of type std::byte*?
The second question: Assume we are working with large structures ( not with int-s) and trying to avoid copying, is it possible to get rid of std::array and std::bit_cast in the code above?