Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint

178 C++ Coding Standards 93. Avoid using static_cast on pointers. Summary Pointers to dynamic objects don't static_cast: Safe alternatives range from using dy- namic_cast to refactoring to redesigning. 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 dan- gerous. 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 De- rived to do its work, examine the chain of calls to identify where the needed type in- formation was lost; often, changing a couple of prototypes leads to an excellent solu- tion that also clarifies the type information flow to you.