标签:reinterpret-cast static-cast c alignment
有人可以解释一下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]);
?
为什么在这里使用两个铸造?
非常感谢.
香港
解决方法:
根据标准(第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 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
.Converting a prvalue of type “pointer to
T1
” to the type “pointer to T2” (whereT1
andT2
are object types and where the alignment requirements ofT2
are no stricter than those ofT1
) and back to its original type yields the original pointer value. The result of any other such pointer conversion is unspecified.
因此,我们可以得出以下结论:
> reinterpret_cast< * T>(ptr)与static_cast< * T>(static_cast< void *(ptr))等效
> static_cast<<>(ptr)并不总是等于ptr,但是reinterpret_cast<>(ptr)总是等于ptr
>如果没有对齐问题,我们可以安全地使用reinterpret_cast
标签:reinterpret-cast,static-cast,c,alignment 来源: https://codeday.me/bug/20191010/1886974.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。