The code you provide doesnt really show an attempt at the issue. You could put together a simple entity manager class that encapsulates these things:
Also depending on your needs it might be worth making the entity manager a singleton (I will also provide code for a singleton template)
Note I haven't tested this code, so not sure if there are any syntax errors.
Code: Select all
#ifndef _ENTITYMANAGER_H
#define _ENTITYMANAGER_H
#include "Entity.h"
#include <list>
class EntityManager : public Singleton<EntityManager>
{
friend class Singleton<EntityManager>;
public:
template<typename T>
T *create()
{
T *e=new T;
entityList.push_back(e);
return e;
}
Entity *findId(int p_id)
{
for(list<Entity*> iter=entityList.begin; iter!=entityList.end; ++iter)
{
Entity* e=*iter;
if(e->id==p_id)
return e;
}
return NULL;
}
void destroy(Entity *p_e)
{
entityList.remove(p_e);
delete p_e;
}
private:
list<Entity*> entityList;
EntityManager(){}
~EntityManager()
{
for(list<Entity*> iter=entityList.begin; iter!=entityList.end; ++iter)
{
Entity* e=*iter;
delete e;
}
entityList.clear();
}
};
#endif
Heres the singleton class I use.
Code: Select all
#ifndef _SINGLETON_H
#define _SINGLETON_H
template<typename T>
class Singleton
{
public:
static T *instance()
{
if(m_singleton==0)
m_singleton=new T();
return m_singleton;
}
void static release()
{
delete m_singleton;
m_singleton = 0;
}
protected:
Singleton(){}
virtual ~Singleton(){}
private:
static T *m_singleton;
Singleton(const Singleton &s);
};
template<typename T> T *Singleton<T>::m_singleton=0;
#endif
Advantages of this approach...
* You don't have to worry about memory leaks as much as this structure ensures all entities are deleted and the end of the program.
* You can easily itterate through all entities by adding a loop similar to that in findId()
* You can add derived classes of Entity to the entity list, as the create() method is a template function. Hence you could do a call such as entityManager->create<Entity>(); or entityManager->create<DerivedEntity>();