其他分享
首页 > 其他分享> > c-std :: aligned_storage的static_cast和reinterpret_cast

c-std :: aligned_storage的static_cast和reinterpret_cast

作者:互联网

有人可以解释一下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 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.

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.

因此,我们可以得出以下结论:

> 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