Counting instances of individual derived classes

前端 未结 10 950
南笙
南笙 2021-01-06 04:42

I\'d like to be able to count instances of classes that belong in the same class hierarchy.

For example, let\'s say I have this:

class A;
class B: pu         


        
10条回答
  •  醉酒成梦
    2021-01-06 05:07

    One way to get around the double-counting when counting objects in the constructor is to count the objects at the point of need, rather than in the constructor, using RTTI. This is minimally intrusive:

    #include 
    #include 
    #include 
    #include 
    
    
    class A
    {
    
    public:
    
        A();
        virtual ~A() { }
    
    };
    
    class B: public A
    {
    
    public:
    
        virtual ~B() { }
    };
    
    class C: public B
    {
    
    public:
    
        virtual ~C() { }
    
    };
    
    template
    struct TypeIdsEqual: public std::binary_function
    {
        bool operator() (const T& obj1, const T& obj2) const
        {
            return typeid(*obj1) == typeid(*obj2);
        }
    };
    
    struct Counter
    {
        static std::vector objects;
    
        static void add(A* obj)
        {
            objects.push_back(obj);
        }
    
        static int count(A* obj)
        {
            return std::count_if(objects.begin(), objects.end(),
                                 std::bind1st(TypeIdsEqual(), obj));
        }
    
    };
    
    std::vector Counter::objects;
    
    // One intrusive line in the base class constructor.  None in derived classes...
    A::A()
    {
        Counter::add(this);
    }
    
    int main(int *argc, char* argv[])
    {
        A* a  = new A;
        B* b  = new B;
        C* c  = new C;
        C* c2 = new C;
        std::cout << Counter::count(*a) << std::endl;  // Output: 1
        std::cout << Counter::count(*b) << std::endl;  // Output: 1
        std::cout << Counter::count(*c) << std::endl;  // Output: 2
    }
    

提交回复
热议问题