Object Registry, LUTs and GC

(1/1)

Richard Marks:
object registry, look up tables and garbage collection

This is something I constantly find myself having to solve, so I decided to make a thread about it.

It shows how to create, use, and destroy a LUT and registry of new-allocated pointers.

A LUT is an associative array where you use one data type to refer to another.
In this case the key is a string, and the value is an unsigned integer.
The registry is just a vector of pointers of some object, in this case its a class called Foo.

Code:

// garbage collection of newd pointers in a vector

#include <cstdio>
#include <cstdlib>
#include <map>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#define COUNT 10
typedef unsigned int ID;

static ID foos = 0;

class Foo
{
public:
ID id_;
Foo(){ id_ = foos; foos++; fprintf(stderr, "created instance %u\n", id_); }
~Foo(){ fprintf(stderr, "destroyed instance %u\n", id_); foos--; }
};

std::vector <Foo*> registry;
std::map <std::string, ID> table;

void spawn()
{
for (int index = 0; index < COUNT; index++)
{
ID id = registry.size();
registry.push_back(new Foo());
std::stringstream buffer;
buffer << "Foo Number " << index + 1;
table[buffer.str()] = id;
}
}

void info()
{
std::map <std::string, ID>::iterator iter = table.begin();
while(iter != table.end())
{
ID id = iter->second;
if (id < registry.size())
{
Foo* foo = registry.at(id);
std::stringstream display;
display << "table[\"" << iter->first << "\"] = " << iter->second << " -> Foo #" << foo->id_;
std::cout << display.str() << std::endl;
}
iter++;
}
}

void collect_garbage()
{
std::vector <Foo*>::iterator iter = registry.begin();
while(iter != registry.end())
{
if (*iter)
{
delete *iter;
registry.erase(iter);
}
else
{
iter++;
}
}
table.clear();
}

int main(int argc, char* argv[])
{
spawn();
info();
collect_garbage();
return 0;
}



Running the program shows that everything works as expected.

Code:

created instance 0
created instance 1
created instance 2
created instance 3
created instance 4
created instance 5
created instance 6
created instance 7
created instance 8
created instance 9
table["Foo Number 1"] = 0 -> Foo #0
table["Foo Number 10"] = 9 -> Foo #9
table["Foo Number 2"] = 1 -> Foo #1
table["Foo Number 3"] = 2 -> Foo #2
table["Foo Number 4"] = 3 -> Foo #3
table["Foo Number 5"] = 4 -> Foo #4
table["Foo Number 6"] = 5 -> Foo #5
table["Foo Number 7"] = 6 -> Foo #6
table["Foo Number 8"] = 7 -> Foo #7
table["Foo Number 9"] = 8 -> Foo #8
destroyed instance 0
destroyed instance 1
destroyed instance 2
destroyed instance 3
destroyed instance 4
destroyed instance 5
destroyed instance 6
destroyed instance 7
destroyed instance 8
destroyed instance 9

Navigation

[0] Message Index