static_cast并reinter pret_cast性病:: aligned_storage [英] static_cast and reinterpret_cast for std::aligned_storage

查看:169
本文介绍了static_cast并reinter pret_cast性病:: aligned_storage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能有人请解释code中的一些关于铸造的<一个href="http://en.cp$p$pference.com/w/cpp/types/aligned_storage">http://en.cp$p$pference.com/w/cpp/types/aligned_storage好吗?

could someone please explain the bit of code about casting in http://en.cppreference.com/w/cpp/types/aligned_storage please?

可以以下code

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

替换

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

为什么这里有两个铸件均采用? 非常感谢。

Why here two casting are used? Thanks a lot.

香港

推荐答案

根据标准(第5.2.10 reinter pret_cast ,第7条):

According to the standard (§ 5.2.10 reinterpret_cast, section 7):

一个指向对象的指针可以显式转换为指针,以二FF erent对象类型。当prvalue v 类型的指针 T1 转换为类型指针 CV T2 ,结果是的static_cast&LT; CV T2 *&GT;(的static_cast&LT; CV无效*&GT;(五)) 如果两个 T1 T2 是标准的布局类型和 T2 并不比那些 T1 的严格。

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.

转换类型的prvalue指针 T1 的类型指针到T2(其​​中 T1 T2 的对象类型,并在 T2 的对准要求并不比那些更严格T1 ),并恢复到原来的类型得到原来的指针值。 其他任何这样的指针转换的结果是unspeci网络版。

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.

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

So, we could make the following conclusion:

  1. reinter pret_cast&LT; * T&GT;(PTR)是eqiuvalent为的static_cast&LT; * T&GT;(的static_cast&LT;无效*&GT;( PTR))
  2. 的static_cast&LT;&GT;(PTR)并不总是等于 PTR ,而 reinter pret_cast&LT;&GT;(PTR)总是等于 PTR
  3. 如果没有对齐的问题,我们可以使用 reinter pret_cast 安全
  1. reinterpret_cast<*T>(ptr) is eqiuvalent to static_cast<*T>(static_cast<void*>(ptr))
  2. static_cast<>(ptr) is not always equal to ptr, but reinterpret_cast<>(ptr) is always equal to ptr
  3. if there is no alignment issues, we can use reinterpret_cast safely

这篇关于static_cast并reinter pret_cast性病:: aligned_storage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆