【发布时间】: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