c++staticstatic-variablestranslation-unit

static variable inside function vs static class variable in c++


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.


Solution

  • 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))