Algorithm for generating a unique ID in C++?

前端 未结 6 1434
走了就别回头了
走了就别回头了 2021-02-02 07:50

What can be the best algorithm to generate a unique id in C++? The length ID should be a 32 bit unsigned integer.

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-02 08:23

    There is little context, but if you are looking for a unique ID for objects within your application you can always use a singleton approach similar to

    class IDGenerator {
       public:
          static IDGenerator * instance ();
          uint32_t next () { return _id++; }
       private:
          IDGenerator () : _id(0) {}
    
          static IDGenerator * only_copy;
          uint32_t _id;
    }
    
    IDGenerator *
    IDGenerator::instance () {
       if (!only_copy) {
          only_copy = new IDGenerator();
       }
       return only_copy;
    }
    

    And now you can get a unique ID at any time by doing:

    IDGenerator::instance()->next ()

提交回复
热议问题