C++ Typecasting VS performance
https://softwareengineering.stackexchange.com/questions/188398
-
05-11-2019 - |
题
Let's say we're designing a video game. We have some sprites on the map and we want to call some method of the particular sprite at some particular position.
We are using one broadly-known C++ framework. It has an GraphicsItem
class, and ALL our sprites are derived from it. Now, framework has a method to get a pointer of the GraphicsItem
at any position on the map.
We've got two options now:
Cast from
GraphicsItem*
to ourSprite*
and callSprite
's method. (We know for sure that all the graphics items on the map are instances ofSprite
)Make some crazy things like Store pointers to
Sprite
in some container, iterate through them, compare address vales and get straightSprite*
without casting.
The question is: what is the best practice in this case? I was always told to avoid typecasting because it means you've got design issues. But how can I change design to avoid typecasting here? And extra iteration over a container with a comparison is just... crazy...
没有正确的解决方案