Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are dynamic_casts safe to remove in production code?

dynamic_casts are slower, but they are safer than static_casts (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_casts?

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.

like image 566
Paul Manta Avatar asked Sep 09 '11 09:09

Paul Manta


People also ask

Is dynamic_ cast a code smell?

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 .

Should I use dynamic_cast?

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).


1 Answers

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!
  /*...*/; 
like image 123
rodrigo Avatar answered Sep 22 '22 06:09

rodrigo