Sachin Sachin - 2 months ago 32
C++ Question

thread safe unique id generation in c++

I was looking for thread safe unique id generation in c++ application life, So I have created following static class.

class Utils {
public :
static int getUid();
};

int Utils::getUid() {
static std::atomic<std::uint32_t> uid;
uid = 0;
return ++uid;
}


Any suggestion, Is this right approach.

Answer

fix it this way:

class Utils {
public :
    static int getUid();
};

int Utils::getUid() {
    static std::atomic<std::uint32_t> uid { 0 };  // <<== initialised
//    uid = 0;    <<== removed
    return ++uid;
}