Best Practice : How to get a unique identifier for the object

Depending on your "uniqueness"-requirements, there are several options:

  • If unique within one address space ("within one program execution") is OK and your objects stay where they are in memory then pointers are fine. There are pitfalls however: If your objects live in containers, every reallocation may change your objects' identity and if you allow copying of your objects, then objects returned from some function may have been created at the same address.
  • If you need a more global uniqueness, for instance because you are dealing with communicating programs or data that is persistent, use GUIDs/UUIds, such as boost.uuid.
  • You could create unique integers from some static counter, but beware of the pitfalls:
    • Make sure your increments are atomic
    • Protect against copying or create your custom copy constructors, assignment statements.

Personally, my choice has been UUIDs whenever I can afford them, because they provide me some ease of mind, not having to think about all the pitfalls.


If the objects need to be uniquely identified, you can generate the unique id in the constructor:

struct Obj
{ 
   int _id;
   Obj() { static int id = 0; _id = id++; }
};

You'll have to decide how you want to handle copies/assignments (same id - the above will work / different id's - you'll need a copy constructor and probably a static class member instead of the static local variable).


When I looked into this issue, I fairly quickly ended up at the Boost UUID library (universally unique identifier, http://www.boost.org/doc/libs/1_52_0/libs/uuid/). However, as my project grew, I switched over to Qt's GUID library (globally unique identifier, https://doc.qt.io/qt-5/quuid.html).

A lesson learned for me though was to start declaring your own UUID class and hide the implementation so that you can switch to whatever you find suitable later on.

I hope that helps.

Tags:

C++