Unique id of class instance

2019-07-27 23:09发布

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?

2条回答
beautiful°
2楼-- · 2019-07-27 23:14

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).

查看更多
祖国的老花朵
3楼-- · 2019-07-27 23:34

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

查看更多
登录 后发表回答