Curiously Recurring Template Pattern - Object Counter

Object Counter

The main purpose of an object counter is retrieving statistics of object creation and destruction for a given class. This can be easily solved using CRTP:

template struct counter { static int objects_created; static int objects_alive; counter { ++objects_created; ++objects_alive; } protected: ~counter // objects should never be removed through pointers of this type { --objects_alive; } }; template int counter::objects_created( 0 ); template int counter::objects_alive( 0 ); class X : counter { // ... }; class Y : counter { // ... };

Each time an object of class X is created, the constructor of counter is called, incrementing both the created and alive count. Each time an object of class X is destroyed, the alive count is decremented. It is important to note that counter and counter are two separate classes and this is why they will keep separate counts of X's and Y's. In this example of CRTP, this distinction of classes is the only use of the template parameter (T in counter) and the reason why we cannot use a simple un-templated base class.

Read more about this topic:  Curiously Recurring Template Pattern

Famous quotes containing the words object and/or counter:

    Did men but consider that the sun, moon, and stars, and every other object of the senses, are only so many sensations in their minds, which have no other existence but barely being perceived, doubtless they would never fall down and worship their own ideas; but rather address their homage to that eternal invisible Mind which produces and sustains all things.
    George Berkeley (1685–1753)

    The individual protests against the world, but he doesn’t get beyond protest, he is just a single protester. When he wants to be more than that, he has to counter power with power, he has to oppose the system with another system.
    Friedrich Dürrenmatt (1921–1990)