Fast dyanamic_cast

Started by
10 comments, last by SiCrane 11 years, 2 months ago

But why do you "need" dynamic_cast<> or its homemade equivalent, as opposed to virtual functions to avoid leaking unneeded type information, segregation of objects of different classes to avoid identifying each one, members and methods providing the information you actually need, and other leaner and cleaner approaches?

Omae Wa Mou Shindeiru

Advertisement

I always wondered about something related. Assuming at some Point you Need to know what class an object actually is of. Then, as far as I understand, I could try dynamic_cast<> to all possible classes. And that's O(n), if n is the number of possible classes. So having a map or hashtable to just look it up should theoretically be faster for large enough n. Is this correct or am I missing a possible way to use dynamic_cast<> efficiently for this?

If you are really hurting by this roll your own and type checking then boils down to a pointer address compare, which you can find in Game Programming Gems 2. This relies on staticly declared pointers in your RTTI capable classes, which you have to register your self. This is all the DECLARE_CLASS(CEnemy, CMoveableObject) macros that you see in the Half-Life codebase (https://developer.valvesoftware.com/wiki/Authoring_a_Logical_Entity).

If std::type_info::hash_code wasn't made deliberately stupid and useless, you wouldn't even need that. You could just use the language's built-in feature. It would even work perfectly for serialization.

Shame that usability was apparently not intended with N2530. A hash code that explicitly gives no guarantee about being the same between different invocations of the same program is entirely useless for the majority of things.

To be fair to the poorly performing dynamic_cast implementations, they generally designed to work in corner situations that game developers rarely run into. Such as dynamic_casts from an object created in a DLL from code in another DLL that may have accidentally declared a type of the same name. In general C++'s dynamic_cast is meant for systems that look very different from games; systems that are long lived and require binary compatibility between revisions are places where dynamic_cast become a more reasonable option. Fortunately for everyone involved these kinds of systems are becoming more frequently implemented in managed languages.

This topic is closed to new replies.

Advertisement