有人可以解释一下有关在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]);
?
为什么这里使用两个铸件?非常感谢。
洪
有人可以解释一下有关在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]);
?
为什么这里使用两个铸件?非常感谢。
洪
According to the standard (§ 5.2.10 reinterpret_cast, section 7):
A pointer to an object can be explicitly converted to a pointer to a different object type. When a prvalue
vof type “pointer toT1” is converted to the type “pointer tocv T2”, the result isstatic_cast<cv T2*>(static_cast<cv void*>(v))if bothT1andT2are standard-layout types and the alignment requirements ofT2are no stricter than those ofT1.Converting a prvalue of type “pointer to
T1” to the type “pointer to T2” (whereT1andT2are object types and where the alignment requirements ofT2are 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.
So, we could make the following conclusion:
reinterpret_cast<*T>(ptr) is eqiuvalent to static_cast<*T>(static_cast<void*>(ptr))static_cast<>(ptr) is not always equal to ptr, but reinterpret_cast<>(ptr) is always equal to ptrreinterpret_cast safely