I want to generate a unique ID for every instance of a given class.
- The ID is of type
unsigned long
- When an instance is deleted, the ID is freed (can be reused)
Now, I've come up with the following implementation:
Class Foo
{
public:
static unsigned std::set<unsigned long> s_usedID;
static unsigned long generateID() // Generate a valid ID
{
static unsigned long id = 0;
while (Foo::isIDUsed(id)) // If all ID are taken, create an infinite loop!
++id;
return id;
}
static void addID(unsigned long id) // Add a given ID to the set of used ID
{
s_usedID.insert(id);
}
static void removeID(unsigned long id) // Remove a given ID from the set of used ID
{
s_usedID.erase(id);
}
static bool isIDUsed(unsigned long id)
{
return s_usedID.count(id) == 1 ? true:false;
}
explicit Foo() : m_id(Foo::generateID())
{
Foo::addID(m_id); // ID is now taken
}
virtual ~Foo()
{
Foo::removeID(m_id); // Free the ID
}
private:
unsigned long m_id;
};
Now for me, this logically works.
- Is there a better way to implement this?
- Are there any optimizations that I could make?
s_userID
could grow quite large if many unique IDs are used. Both of these things would cause me personally to rethink this algorithm. \$\endgroup\$