Friday 15 August 2014

casting - C++: Safe way to cast an integer to a pointer -


I need to change an integral type that contains an address for the actual pointer type. I can use reinterpret_cast as follows:

  MyClass * mc1 = reinterpret_cast & lt; MyClass * & gt; (The_integer);  

However, to see if a MyClass object is actually in fact, no run-time checks. I want to know whether there is any benefit in using a zero * (reinterpret_cast) first and using dynamic_cast on the result. Like this:

  zero * p = reinterpret_cast & lt; Zero * & gt; (The_integer); MyClass * mc1 = dynamic_cast & lt; MyClass * & gt; (P); Emphasis (MC1! = Null);  

Is there any use in using another method?

Checking on dynamic_cast in different ways ++ has been implemented in the implementation; If you want an answer for your specific implementation, then you should mention what implementation you are using. In general, the only way to answer the question is to refer to the ISO standard C ++.

Calling dynamic_cast is invalid on your reading of a standard;

If T is an indicator type, then a V A rvalue of the indicator will be "<< Pre> dynamic_cast < T & gt; (V)

/ P>

(from ISO C ++ standard 5.2.7.2) zero is not a full class type, so the expression is invalid.

The interesting thing is that any object being inserted is allowed to be zero indicator, i.e.

  zero * foo = dynamic_cast & Lt; Zero * & gt; (Some_pointer);  

In this situation, dynamic_code is always successful, and the resulting value is an indicator for the most derived object v .


No comments:

Post a Comment