How to Get a Unique Identifier For Object in C++?
Prerequisite: Classes and Objects in C++
A single entity within a given system is identified by a string of numbers or letters called a unique identifier (UID). UIDs enable addressing of that entity, allowing access to and interaction with it. There are a few choices, depending on your “uniqueness” requirements:
Pointers are acceptable if unique inside one address space (also known as “within one program execution”) and your objects remain in place in memory. There are dangers, though: If your objects are contained, each reallocation could alter their identity, and if you permit copying, objects returned from a function might have originated from the same address.
Use GUIDs/UUIDs, such as boost.UUID, if you require a greater degree of global uniqueness, for instance, because you are working with communicating applications or persistent data. From a static counter, you could make unique numbers, but watch out for these pitfalls:
- Make sure your increments are atomic.
- Create custom copy constructors or assignment statements to prevent copying.
To keep track of the subsequent identifier to use, utilize a static variable. As long as you have a function that can produce unique values, you can use anything as the unique identifier. In Example 8-8, we have used a static int, but you can use anything.
The identifiers are not reused in this situation until the int’s maximum capacity is reached. Once an object is deleted, its unique value is lost until the program is restarted or the object’s identifier value reaches its maximum and flips over. This program’s singularity can have some intriguing benefits.
1 2 3
Explanation: In the above program, we have created a class and initialized its 3 objects, and given a unique ID to each of them as shown in the output.
Please Login to comment...