When programming games, I used to store all game Objects in a std::vector with initialized and fixed size. Recently I felt the need for some inheritance among the game object classes.
So lets assume I have like 40 classes derived from my class Enemy. If I want to store objects/instances of those classes in a vector, I only have the option of storing them as vector Enemy* right? So the only thing thats contiguously allocated are the pointers, right? So I still will have a lot of cache misses when those need to be dereferenced, right?
Is there any "best practice" way, of storing derived classes in coniguous allocated memory, so that looping through them takes the minimum amount of time?
std::vector<std::unique_ptr<Enemy>>
by default - so you don't have to worry about the memory management yourself. – Mindyminevector<unique_ptr<Enemy>>
and benchmark. If you do need to go this route, this simplest/most feasible approach with such a large number of derived classes, is to use a custom allocator to ensure that all of the Enemies get constructed in a contiguous block of memory. You would still use a vector of unique_ptr's just with a custom deleter, and use some other function instead ofmake_unique
. – Mechanist