Safe Recurison?

Ok so I have a function call that moves an Entity from one vector to another, and if one doesn't exist then it creates one and moves it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
std::vector<std::unique_ptr<Entity>> ActiveEntities;
std::vector<std::unique_ptr<Entity>> EntityPool;

// Creates a generic entity in the entity pool
void EntityManager::CreateEntity()
{
    EntityPool.emplace_back(std::unique_ptr<Entity>(new Entity(GenerateID())));
};

// Moves an inactive entity to the active pool and returns it's id
int EntityManager::AddEntity()
{
    for(int i = 0; i < EntityPool.size; i++)
    {
        if(EntityPool[i])
        {
            ActiveEntities.push_back(std::move(EntityPool[i]));
            return EntityPool[i].get()->GetUID;
        }
        else
        {
            CreateEntity();
            AddEntity();
        }
    }
};


In this case it checks the entity pool for an entity, if one exists it moves it to the active entities and then returns the unique id, if one doesn't exist it creates one then calls itself to run the check again to verify and move the new entity.

My question is, is this a valid form of recursion since it only incurs a single loop of recursion, or should I reform the entire system to work differently? If so, how do you set this up in a way that does not cause recursion?
1
2
            ActiveEntities.push_back(std::move(EntityPool[i]));
            return EntityPool[i].get()->GetUID; //but... you just move it 
in the standard library- moving implies that the moved-from object is left in a valid but unspecified state



If the first elements is "empty", then it would make a recursive call and check the first element again (that would remain "empty"). So stack overflow.

> how do you set this up in a way that does not cause recursion?
¿why is line 23 needed?
haha.... thanks for noticing, I was half asleep this morning when I wrote this.... will have to fix that.

As for line 23, it needs that because there is a separate function that handles the creation of new entities, and a separate one for moving them between the 2 pools. The AddEntity() function checks the entitypool for an entity, if one exists it moves it to the activepool, if one doesn't it simply calls the function that creates a new entity and adds it to the entity pool, thus needing to go back over and search the entitypool again. I suppose I could simply create the entity and move it instead though.... but the problem is I could be moving it to either the pool or the active, so how do I tell this separate function which vector to put the pointer in?

I suppose I should just rethink this entirely....
> thus needing to go back over and search the entitypool again
you insert at the end, the only thing that may change is the end.
there is no need to go back, you already know what those elements are and they are useless for you.
just continue.
Topic archived. No new replies allowed.