Algorithm for generating a unique ID in C++?

前端 未结 6 1428
走了就别回头了
走了就别回头了 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:34

    Here's the simplest ID I can think of.

    MyObject obj;
    uint32_t id = reinterpret_cast(&obj);
    

    At any given time, this ID will be unique across the application. No other object will be located at the same address. Of course, if you restart the application, the object may be assigned a new ID. And once the object's lifetime ends, another object may be assigned the same ID.

    And objects in different memory spaces (say, on different computers) may be assigned identical IDs.

    And last but not least, if the pointer size is larger than 32 bits, the mapping will not be unique.

    But since we know nothing about what kind of ID you want, and how unique it should be, this seems as good an answer as any.

提交回复
热议问题