jeudi 14 mars 2019

Objects counters

I would like to have to counters for each class type that that was ever instantiated. As a starting point someone sugested this approach as an example:

class Person
{
public:
    Person() {
        objects.push_back(this);
    }
    virtual ~Person() {
        objects.erase(this);
    }

static void print_types()
{
    for (auto pers : container)
    {
        std::cout << typeid(*pers).name() << "\n";
    }
}
private:
    static std::set<const Person*> objects;
};

class Employee : public Person
{
};


class Employee2 : public Employee
{
};

Each time one of the classes is instatiated I keep track of the objects and I can use print_types() to know how many of which type I've created so far. Notice that Employee2 inherits from Employee and not from Person (i need this to work for chain inheritance)

I would like to extend this so that I have two counters per type: created and alive. The problem is that you can't easily mantain the counters from the constructor/destructor of the base class, Person, because typeid(*this) will return the base class type when called from constructor/destructor.

Another suggestion was to use CRTP pattern but this doesn't work when you use chained inheritance.

Is there another way to implement such counters ?

Aucun commentaire:

Enregistrer un commentaire