1

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.

Community
  • 1
  • 1
ikku100
  • 809
  • 1
  • 7
  • 16
  • 4
    FWIW, you're right. Neither implementation is thread-safe. – Andrew Henle May 04 '16 at 15:55
  • Just to make it more clear because for some reason people focus on thread safety (I'm sorry if my question is vague): I'm asking why either method would be better. If they are just as thread unsafe, then thread safety shouldn't enter the discussion. – ikku100 May 04 '16 at 16:18

2 Answers2

2

To make it thread-safe you should change to std::atomic<unsigned> mID, and write your function as

return mID.fetch_add(1);

Which version you choose shouldn't matter, although in my opinion the free function would be the one I'd prefer as it's not possible to access the variable outside of the function.

DeiDei
  • 10,205
  • 6
  • 55
  • 80
Viktor Sehr
  • 12,825
  • 5
  • 58
  • 90
1

The difference is scope/visibility of the static variable. A class member can be shared by more than one method, the variable in the method cannot.

On the principle that data should be as private as possible, the static variable in the method is safer if it meets your needs.

For a discussion of thread safety when initializing the variable, see this question., but using the variable is not thread safe unless you take some steps to insure that it is protected (either use and atomic (preferred for a simple value), or protect it with a mutex (if there is more than one piece of data that should be protected))

Community
  • 1
  • 1
Dale Wilson
  • 9,166
  • 3
  • 34
  • 52