Counting instances of individual derived classes

前端 未结 10 850
南笙
南笙 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 04:56

    This is a simple counter I use each so often for debugging:

    // counter.hpp
    #ifndef COUNTER_HPP
    #define COUNTER_HPP
    
    template 
    class Counter
    {
    public:
        Counter( bool do_count = true ) : counted(do_count) 
        { if ( counted ) get_count()++; }
        ~Counter() { if (counted) --count_; }
    
        static unsigned long count() { return count_; }
        static unsigned long& get_count() { 
           static unsigned long count=0;
           return count;
        }
    private:
        bool do_count;
    };
    #endif 
    

    The usage is simple, just inherit from it:

    class BaseClass : public Counter
    {
    public:
       explicit BaseClass( bool do_count = true ) 
          : Counter( do_count )
       {}
    };
    class DerivedClass : public BaseClass, Counter
    {
    public:
       explicit DerivedClass( bool do_count = true )
          : BaseClass(false), Counter(do_count)
       {}
    };
    

    User code will call a parameterless constructor:

    int main() {
       BaseClass b; // will call Counter(true)
       DerivedClass d; // will call Counter(false), Counter(true)
    }
    

提交回复
热议问题