DekGenius.com
Team LiB   Previous Section   Next Section
reinterpret_cast operator Cast for unsafe pointer conversions

postfix-expr := reinterpret_cast < type-id > ( expression )

The reinterpret_cast operator performs potentially unsafe type casts. It is most often used to cast a pointer to a different pointer type. Casting a pointer to a different pointer and back is usually safe and yields the original value. The limitations are that object pointers can be cast only to object pointers with similar or stricter alignment requirements, and function pointers can be cast only to function pointers. Pointers-to-members can be cast only to pointers-to-members. You can cast an integer to a pointer and vice versa. In all cases, the destination pointer must be large enough to hold the result. Casting a null pointer results in a null pointer of the destination type. Any other cast results in undefined behavior.

Example

template<typename T>
unsigned long addressof(const T& obj)
{
  return reinterpret_cast<unsigned long>(&obj);
}

See Also

const_cast, dynamic_cast, expression, static_cast, Chapter 3

    Team LiB   Previous Section   Next Section