I'm trying to create a Data
class whose objects each hold a unique ID.
I want the 1st object's ID to be 1, the 2nd to be 2, etc. I must use a static int
, but all the objects have the same ID, not 1, 2, 3...
This is the Data
class:
class Data
{
private:
static int ID;
public:
Data(){
ID++;
}
};
How can I do it so the first one ID would be 1, the second would be 2, etc..?
If the ID is static, then it will have the same value for all class instances.
If you want each instance to have sequential id values, then you could combine the static attribute with a class variable, like this:
If the application will be multi threaded, then you'll have to synchronize it with something like a pthread mutex.
This:
Besides a static counter, you also need an instance-bound member.
Initialization of static variable within a function is allowed so a solution can be something like this
Each instance of
Data
needs its own non-static member variable that stores its ID. Astatic
variable can be used to store the last used ID which would be incremented in the constructor ofData
.Instead of a
static
counter, which is not thread-safe, consider using boost's uuid:where is the instance(non static) id here? you need to declare a new instance ID field like this
then in your constructor do
in an interlocked or other thread-safe way