Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in C++, how to use a singleton to ensure that each class has a unique integral ID?

I have a bunch of C++ classes.

I want each class to have something like:

static int unique_id;

All instances of a same class should have the same unique_id; different classes should have different unique_id's.

The simplest way to do this appears to be threading a singleton through the classes.

However, I don't know what's called when for static class members / things that happen before main.

(1) if you have a solution that does not involve using singleton, that's fine too

(2) if you have a solution that gives me a :

int unique_id(); 

that is fine too.

Thanks!

like image 941
anon Avatar asked Jan 31 '10 18:01

anon


1 Answers

Have a class that increments it's ID on each creation. Then use that class as a static field in each object that is supposed to have an ID.

class ID
{
    int id;
public:
    ID() {
        static int counter = 0;
        id = counter++;
    }

    int get_id() {  return id; }
};

class MyClass
{
    static ID id;
public:
    static int get_id() 
    {
        return id.get_id();
    }
};
like image 130
Kornel Kisielewicz Avatar answered Oct 24 '22 14:10

Kornel Kisielewicz