Unique id of class instance

2019-07-27 23:01发布

问题:

I have a class like this:

class ExampleClass {

private:
    int _id;
    string _data;

public:
    ExampleClass(const string &str) {
        _data = str;
    }
    ~ExampleClass() {

    }
    //and so on...    

}

How can I add unique(!) integer identifier (_id) for every instance of the class without using global variable?

回答1:

Use a private static member int, is shared among all instance of the class. In static int in the constructor just increment it, and save it's value to your id member;

class ExampleClass {

private:
    int _id;
    string _data;
    static int counter=0;
public:
    ExampleClass(const string &str) {
        _data = str;
         id=++counter;
    }

Update:

You will need to take consideration in your copy constructor and operator= what behavior you want (depends on your needs, a new object or an identical one).



回答2:

You can hide a static data in your class, which will provide the unique id.

Example:

class ExampleClass {

private:
    int _id;
    static int idProvider;
public:
    ExampleClass(const string &str) 
          : _id(++idProvider)
    {} 
}

int ExampleClass::idProvider = 0;

the logic is everytime you created an object of ExampleClass it will increment the idProvider which will then assign as a unique id to your id