For a unique id for some object I can create a counter in two ways but I don't know which one is better while they are quite different in code (though maybe not in byte code, I have no idea).
The first way would be to have some function which uses a static variable:
Header:
unsigned int GetNextID();
cpp:
unsigned int GetNextID()
{
static unsigned id{0};
return id++;
}
The other option:
Header:
class UniqueIdGenerator
{
public:
static unsigned int GetNextID();
private:
static unsigned int mID;
}
cpp:
unsigned int UniqueIdGenerator::mID = 1;
unsigned int UniqueIdGenerator::GetNextID()
{
return ++mID;
}
FYI, I've read that the former is not thread safe, but I don't see why the latter would be either. If anything, I like the simple function more as it's simpler & shorter.