instance counting

From: stephan beal (stephan_at_s11n.net)
Date: 10/31/03


Date: Fri, 31 Oct 2003 12:46:08 +0100

Good morning, C++ers,

A couple days ago i came across a useful trick for counting instances of a
given class, and i thought i'd pass it on:

Conventionally, as described in several books, to do instance counting we
subclass some base type and add a counter to that base class. IMO that is
completely unnecessary:

/**
       Utility function to help keep an instance count of T.
*/
template <typename T>
unsigned long & inst_count() { static unsigned long c = 0; return c; }

Then simply do this in the ctors:
++inst_count<MyType>();

and in the dtor:
--inst_count<MyType>();

This offers a feature the conventional approach does not: it allows us to
track instance counts separately for, e.g. A and B, when B subclasses A.
That it, if we use some "pure A" objects and some B objects we can
independently track A and B counts by using inst_count<> in both A and B.

Of course, this approach does suffer from the potential problem of client
code doing:

inst_count<MyType>() = 10;

but i think that's far-fetched enough that it can be essentially ruled out.

-- 
----- stephan beal
http://s11.net/
Registered Linux User #71917 http://counter.li.org
I speak for myself, not my employer. Contents may 
be hot. Slippery when wet. Reading disclaimers makes
you go blind. Writing them is worse. You have been Warned.