Is the following C++ casting correct?
I read a few posts on the usage of static and dynamic casts specifically from When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?
I have a doubt regarding the usage of cast in the following manner. Can someone verify the below mentioned code:-
This is upward casting in inheritance hierarchy
template<class Base, class Derived>
inline Handle<Base> STATIC_CAST(Handle<Derived> hd) {
开发者_JAVA百科 Handle<Base> hb;
Derived* dp = hd.get(); // Assume this gives pointer of derived class object
Base* bp = static_cast<Base*> (dp);
if(bp) {
hb = Ptr2Handle(bp); // Assume this give reference to Handle
}
return hb;
}
*Derived is actually the derived class from class Base.
What about downward casting in the following code?
template<class Base, class Derived>
inline Handle<Derived> DYNAMIC_CAST(Handle<Base> hb) {
Handle<Derived> hd;
Base* bp = hb.get();
Derived* dp = dynamic_cast<Derived*> (bp);
if(dp) {
hd = Ptr2Handle(dp);
}
return hd;
}
What will be the impact if the above two MACROS are passed with Base and Derived class swapped?
If Base
is really a base class of Derived
, there's absolutely no need for any cast, meaning that static_cast
in the above code is absolutely superfluous. It doesn't achieve anything a mere assignment wouldn't do implicitly. Moreover, in upcasts (from derived to base), dynamic_cast
is absolutely equivalent to static_cast
, meaning that dynamic_cast
wouldn't achieve anything new either.
Actually, by placing an explicit static_cast
cast in that code, its author enabled forceful "reverse" casts (downcasts). I.e. you can use this code to cast from base classes to derived classes. I don't know whether this was the intent (I doubt it was, judging by the template parameter names), and if it wasn't it might be a good idea to remove the cast entirely, since it is dangerous.
If, despite my doubts, the code was actually supposed to support downcasts, then dynamic_cast
might indeed help to catch potential errors. However, keep in mind that dynamic_cast
works in downcasts with polymorphic class types only.
A static_cast upward (in direction of ancestors) in hierarchy is always legal. That cast will be legal (assuming Base and Derived are classes) iff Base is a base class of Derived.
Assuming Derived
is derived from Base
the cast although correct is unnecessary. You can directly assign the result of hd.get()
to Base*
精彩评论