static_cast并reinter pret_cast性病:: aligned_storage [英] static_cast and reinterpret_cast for std::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 的对齐要求code>并不比那些
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 toT1
" is converted to the type "pointer tocv T2
", the result isstatic_cast<cv T2*>(static_cast<cv void*>(v))
if bothT1
andT2
are standard-layout types and the alignment requirements ofT2
are no stricter than those ofT1
.
转换类型的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:
-
reinter pret_cast&LT; * T&GT;(PTR)
是eqiuvalent为的static_cast&LT; * T&GT;(的static_cast&LT;无效*&GT;( PTR))
-
的static_cast&LT;&GT;(PTR)
并不总是等于PTR
,而reinter pret_cast&LT;&GT;(PTR)
总是等于PTR
- 如果没有对齐的问题,我们可以使用
reinter pret_cast
安全
reinterpret_cast<*T>(ptr)
is eqiuvalent tostatic_cast<*T>(static_cast<void*>(ptr))
static_cast<>(ptr)
is not always equal toptr
, butreinterpret_cast<>(ptr)
is always equal toptr
- if there is no alignment issues, we can use
reinterpret_cast
safely
这篇关于static_cast并reinter pret_cast性病:: aligned_storage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!