r/learncpp • • 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?

4 Upvotes

9 comments sorted by

View all comments

Show parent comment

1

u/lead999x Oct 20 '20

I think I understand. Thanks for explaining. And I will watch the videos as soon as I can.

1

u/druepy Oct 20 '20

Yeah. Definitely watch the videos and look up some blogs. Learn for yourself vs trusting some random Reddit user (me). I've been learning about this stuff, but I'm still only human.

As far as the algorithmic analysis vs implementation. This is something I struggled with for a while. How can an operations that's O(n) be faster than an operation that's O(1)? Algorithmic complexity is a mathematical tool to describe the runtime of an algorithm as a function of its input independently of implementation.

It can get confusing when you realize that an O(n) operation can be faster than an O(1) operation in an implementation. An example would be using a vector as a set instead of a binary tree (like std::set). std::set has the better insertion times from an algorithmic perspective. But, it tends to perform relatively poorly. The binary tree suffers from the same issue a linked list does. It has pointers to pointers to pointers to pointers for its node structure. The vector, already has everything in contiguous memory.

The processor is fast, but the memory is relatively slow. The processor can waste thousands of cycles by waiting for memory to be loaded. This is a big reason why we see the implementations seem to defy algorithmic complexity.