Counting instances of individual derived classes

前端 未结 10 951
南笙
南笙 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条回答
  •  猫巷女王i
    2021-01-06 05:03

    The current solutions all seem to count in constructors, and therefore also count in constructors of base type. (except Mykola, but that solution has an implicit conversion from bool - bad) This double-counting wasn't desired. The tricky part, though, is that during the construction of a derived type, the object temporary has intermediate base types. And with virtual base classes, this situation is even worse. In that case, the intermediate type isn't even well-defined.

    Ignoring such transients, there are a few solutions to the double-counting:

    • Use a flag to disable counting
    • Use a protected base class constructor which doesn't count
    • Decrease the instance count of your base classes in derived constructors '*(this->base::count)--`
    • Keep the counts in a dedicated virtual base class.

    The latter option (virtual base class) is probably the nicest; the compiler will enforce it's initialized once and only once, from the final ctor.

    class counter {
        template struct perTypeCounter { static int count =  0; }
        int* count; // Points to perTypeCounter::count
    
        protected:
        template counter(MostDerived*) 
        {
            count = &perTypeCounter::count;
            ++*count;
        }
        ~counter() { --*count; }
    };
    

提交回复
热议问题