Recursive is trivial. Something like (not real code):
class Entity
{
public:
std::vector<Entity*> refs;
bool marked;
};
void mark(Entity *entity)
{
entity->marked = true;
for(auto &r: entity->refs)
{
if(!r->marked) mark(r);
}
}
void gc(std::vector<Entity*> roots)
{
// all entities mark set to false
for(auto &r: roots)
{
mark(r);
}
for(auto &r: heap)
{
if(!r->marked) reclaim(r);
}
}
Running out of stack space isn't really a concern for my little toy language, but I believe it is always possible to convert a recursion to an iteration so was wondering if anyone could help me stumble over this little mental obstacle?By the way, I am aware there are better algorithms for GC than this naive approach. I'm not worried about that at the moment, just want to get a basic system working first so I have something to profile against when I improve it later.
Thanks.