开发者

reinterpret_cast

In the C++ Without Fear: A Beginner's Guide That Makes You Feel Smart book, and in chapter (8), it mentions the following about reinterpret_cast

....converts from one pointer type (int) to another (char*). Because the cast changes the way the data pointed to is interpreted, it is called reinterpret_cast, as opposed to static_cast.*

开发者_StackOverflow社区

Can you describe this paragraph here? Especially the reason for the way the operation is named?

Thanks.


Basically, reinterpret_cast reinterprets the bit pattern at a specific location as a different type.

See for example here: http://publib.boulder.ibm.com/infocenter/lnxpcomp/v7v91/index.jsp?topic=%2Fcom.ibm.vacpp7l.doc%2Flanguage%2Fref%2Fclrc05keyword_reinterpret_cast.htm

The reinterpret_cast operator produces a value of a new type that has the same bit pattern as its argument.

A static cast converts the argument instead of just reinterpreting it. You can try this out by static_casting an int to float and reinterpret_casting an int to float. The result will be totally different.


There's nothing fancy here. it's really just intended to reinterpret something.

From standard 5.3.10, reinterpret_cast is aimed to cater the following cases:

  • A pointer can be explicitly converted to any integral type large enough to hold it.
  • A value of integral type or enumeration type can be explicitly converted to a pointer.
  • A pointer to a function can be explicitly converted to a pointer to a function of a different type.
  • A pointer to an object can be explicitly converted to a pointer to a different object type.
  • Converting a pointer to a function into a pointer to an object type or vice versa is conditionally-supported.
  • The null pointer value (4.10) is converted to the null pointer value of the destination type.
  • A prvalue of type “pointer to member of X of type T1” can be explicitly converted to a prvalue of a different type “pointer to member of Y of type T2” if T1 and T2 are both function types or both object types.
  • An lvalue expression of type T1 can be cast to the type “reference to T2” if an expression of type “pointer to T1” can be explicitly converted to the type “pointer to T2” using a reinterpret_cast. That is, a reference cast reinterpret_cast < T& >(x) has the same effect as the conversion *reinterpret_cast< T* >(&x) with the built-in & and * operators (and similarly for reinterpret_cast< T&& >(x)).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜