Discussion
Team LiB
Previous Section Next Section

Discussion

Consider replacing uses of static_cast with its more powerful relative dynamic_cast, and then you won't have to remember when static_cast is safe and when it's dangerous. Although dynamic_cast can be slightly less efficient, it also detects illegal casting (and don't forget Item 8). Using static_cast instead of dynamic_cast is like eliminating the stairs night-light, risking a broken leg to save 90 cents a year.

Prefer to design away downcasting: Refactor or redesign your code so that it isn't needed. If you see that you are passing a Base to a function that really needs a Derived to do its work, examine the chain of calls to identify where the needed type information was lost; often, changing a couple of prototypes leads to an excellent solution that also clarifies the type information flow to you.

Excessive downcasts might indicate that the base class interface is too sparse. This can lead to designs that define more functionality in derived classes, and then downcast every time the extended interface is needed. The one good solution is to redesign the base interface to provide more functionality.

If, and only if, the overhead of the dynamic_cast actually matters (see Item 8), consider defining your own cast that uses dynamic_cast during debugging and static_cast in the "all speed no guarantees" mode (see [Stroustrup00]):



template<class To, class From> To checked_cast( From* from ) {


 assert( dynamic_cast<To>(from) == static_cast<To>(from) && "checked_cast failed" );


 return static_cast<To>( from );


}





template<class To, class From> To checked_cast( From& from ) {


 assert( dynamic_cast<To>(from) == static_cast<To>(from) && "checked_cast failed" );


 return static_cast<To>( from );


}



This little duo of functions (one each needed for pointers and references) simply tests whether the two casts agree. We leave it up to you to customize checked_cast for your needs, or to use one provided by a library.

    Team LiB
    Previous Section Next Section