dynamic_cast
s are slower, but they are safer than static_cast
s (when used with object hierarchies, of course). My question is, after I've ensured in my debug code that all (dynamic) casts are correct, is there any reason for me not to change them to static_cast
s?
I plan on doing this with the following construct. (Btw, can you think of a better name than assert_cast
? Maybe debug_cast
?)
#if defined(NDEBUG)
template<typename T, typename U>
T assert_cast(U other) {
return static_cast<T>(other);
}
#else
template<typename T, typename U>
T assert_cast(U other) {
return dynamic_cast<T>(other);
}
#endif
Edit: Boost already has something for this: polymorphic_downcast
. Thanks to PlasmaHH for pointing that out.
Yes, dynamic_cast is a code smell, but so is adding functions that try to make it look like you have a good polymorphic interface but are actually equal to a dynamic_cast i.e. stuff like can_put_on_board .
dynamic_cast is "bad design" for the simple reason that it violates this purpose, since you need your object to be of some derived type, so it doesn't suffice to know the base type of it. That being said it still has its use (especially as the world isn't as simple as Java likes it to be).
No! dynamic_cast
does more than just casting. It can check the runtime type of the object. But it can also traverse hierarchies that are unknown to the compiler, but are only known in runtime. static_cast
cannot do that.
For example:
class A1
{
virtual ~A1() {}
};
class A2
{
virtual ~A2() {}
};
class B : public A1, public A2
{ };
A1 *a1 = new B;
A2 *a2 = dynamic_cast<A2*>(a1); //no static_cast!
A1 *x = ...;
if (B *b = dynamic_cast<B*>(x)) //no static_cast!
/*...*/;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With