gpt4 book ai didi

c++ - std::aligned_storage 的 static_cast 和 reinterpret_cast

转载 作者:可可西里 更新时间:2023-11-01 15:24:26 26 4
gpt4 key购买 nike

有人可以解释一下关于在 http://en.cppreference.com/w/cpp/types/aligned_storage 中进行转换的代码吗?好吗?

可以如下代码

return *static_cast<const T*>(static_cast<const void*>(&data[pos]));

替换为

 return *reinterpret_cast<const T*>(&data[pos]);

?

这里为什么用了两个casting?非常感谢。

最佳答案

根据标准(§ 5.2.10 reinterpret_cast,第 7 节):

A pointer to an object can be explicitly converted to a pointer to a different object type. When a prvalue v of type “pointer to T1” is converted to the type “pointer to cv T2”, the result is static_cast<cv T2*>(static_cast<cv void*>(v)) if both T1 and T2 are standard-layout types and the alignment requirements of T2 are no stricter than those of T1.

Converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value. The result of any other such pointer conversion is unspecified.

因此,我们可以得出以下结论:

  1. reinterpret_cast<*T>(ptr)相当于static_cast<*T>(static_cast<void*>(ptr))
  2. static_cast<>(ptr)并不总是等于 ptr ,但是reinterpret_cast<>(ptr)始终等于 ptr
  3. 如果没有对齐问题,我们可以使用reinterpret_cast安全地

关于c++ - std::aligned_storage 的 static_cast 和 reinterpret_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19300142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com