[英]Any useful difference between std::bit_cast and std::start_lifetime_as?
std::bit_cast
is apparently being introduced in c++20. std::bit_cast
显然是在 c++20 中引入的。 and std::start_lifetime_as
is proposed for c++23 (from P0593R5 ).和std::start_lifetime_as
建议用于 c++23(来自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.我只是在观看了关于类型双关语的 cppcon 2019 讲座后才听说它们,而且我在谷歌上找不到关于start_lifetime_as
的太多信息。 I'm hoping someone else who sees this might know more.我希望看到这个的其他人可能会知道更多。
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).答案很简单: bit_cast
返回一个值,而start_lifetime_as
“改变” memory(以抽象机器中存在但预计不会影响任何物理位的方式)。 You use the former to (once) interpret an existing object as a set of bits;您使用前者(一次)将现有的 object 解释为一组位; you use the latter to (permanently) interpret existing bits as an object.您使用后者(永久)将现有位解释为 object。
std::bit_cast
copies the bits of its argument to a new value of a different type. std::bit_cast
将其参数的位复制到不同类型的新值。
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. myFloat
、 asUint
和asBytes
是具有不同地址的独立变量。 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. std::start_lifetime_as
不做任何事情。 It just informs the compiler that it can treat a range of memory as if it contained an array of the specified type.它只是通知编译器它可以将 memory 的范围视为包含指定类型的数组。 This then allows the developer use that memory as an array without triggering undefined behaviour.然后,这允许开发人员将 memory 用作数组,而不会触发未定义的行为。 It doesn't physically modify the memory passed to it and it doesn't return anything.它不会对传递给它的 memory 进行物理修改,也不会返回任何内容。 It's purely for C++ object model bookkeeping.它纯粹用于 C++ object model 簿记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.