r/learncpp • u/hawidoit • Oct 18 '20
Trying to create an entity manager
Hi,
I have a bunch of classes (Door, Monster, Human)
And the way I want to be able to manage them is via a singleton EntityManager class that ends up looking like this:
EntityManager {
vector<Door> entities;
vector<Human> entities;
}without any code duplication.
I want to be able to write:
Door* EntityManager<Door>::createObject();which pushes the object onto the vector and returns the address;
I've struggling to implement this without running into weird segfaults whenever I use the EntityManager in multiple translation units. I assume I'm misunderstanding how templating works.
Here's essentially what I've come up with:
template <typename T>
class EntityManager {
vector<T> entities;
T* createObject();
};This works within the same translation unit no problem, but when I attempt to use the same EntityManager (such as EntityManager<Door>) across TUs, I get a segfault... I cannot for the life of me figure out why.
Does anyone have any advice or can point me in the right direction into avoid code duplication while achieving something like this via templates?
View all comments
Show parent comment
2
u/druepy Oct 20 '20
There's algorithmic complexity, and then there's implementation. Watch those videos. They'll help explain some stuff.
As far as the list and vector example. You are right in that only the pointer is in the cache. This makes it so the CPU has a high chance at prefetching the object it points to. However, with linked lists, the chances of the next pointer being in cache is low. This pessimise the branch prefetcher.
I can find more stuff tomorrow for this. You're not wrong in what you're saying. The list is valid. Using some associative container is also valid. My point boils down to that I still think a vector of pointers would be better than a list. Especially with prefetching.
I misspoke about the two pointer indirections. The example I was thinking of is when the CPU can be several moves ahead. If you have a vector of pointers then the next several pointers are in cache. If you have a list of pointers, then you are most likely jumping all over the place to load the object you desire.