【问题标题】:static_cast and reinterpret_cast for std::aligned_storagestd::aligned_storage 的 static_cast 和 reinterpret_cast
【发布时间】:2013-10-18 11:18:52
【问题描述】:

有人可以解释一下关于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]);

?

为什么这里使用了两个强制转换? 非常感谢。

洪

【问题讨论】:

  • 我怀疑这是适当的可移植性/标准一致性所必需的,因为标准中没有指定reinterpret_cast 的结果。在实践中,它们可能在所有或几乎所有实现中都做同样的事情。
  • 两者在C++11中是等价的。
  • @SteveJessop:我认为这是一个答案。
  • @JohnDibling:如果我确定它是正确的(首先reinterpret_cast 未针对该工作指定,其次这是示例代码使用这两个强制转换的原因) .如果std::aligned_storage 真的给您提供了距离可用还有两个演员表的东西,那么这有点糟糕。
  • 我首先在那个 cppreference 示例中使用了reinterpret_cast,但在阅读了从chat.stackoverflow.com/transcript/message/10437436#10437436 和 TR1-age 开始的休息室讨论后,我更改为这个 static_cast 链,并带有评论“避免正式的 UB”发布stackoverflow.com/a/1082398/273767 .. 但我可能过于谨慎了。如果有人发布了令人信服的答案,请随时更改。

标签: c++ alignment reinterpret-cast static-cast


【解决方案1】:

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

指向对象的指针可以显式转换为指向不同对象类型的指针。当类型为“指向T1”的纯右值v 转换为类型“指向cv T2”的指针时,如果T1 和T2 都是标准布局,则结果为static_cast&lt;cv T2*&gt;(static_cast&lt;cv void*&gt;(v)) T2 的类型和对齐要求并不比T1 严格。

将“指向T1”类型的prvalue转换为“指向T2的指针”类型(其中T1和T2是对象类型,T2的对齐要求并不比T1) 并返回其原始类型会产生原始指针值。 未指定任何其他此类指针转换的结果。

所以,我们可以得出以下结论:

  1. reinterpret_cast&lt;*T&gt;(ptr) 等同于 static_cast&lt;*T&gt;(static_cast&lt;void*&gt;(ptr))
  2. static_cast&lt;&gt;(ptr) 并不总是等于 ptr,但 reinterpret_cast&lt;&gt;(ptr) 总是等于 ptr
  3. 如果没有对齐问题,我们可以安全地使用reinterpret_cast

【讨论】:

    猜你喜欢
    • 2015-04-07
    • 2016-05-28
    • 1970-01-01
    • 2011-10-14
    • 2015-03-27
    • 2013-03-05
    • 1970-01-01
    • 2017-05-10
    • 2016-02-12
    相关资源
    最近更新 更多