Create template class with a static counter.
Each object in your application would then extend this template class.
When constructor is called increment static count (static variable is per class - shared by all objects of that class).
For example see Object Counter using Curiously recurring template pattern:
template <typename T>
struct counter
{
counter()
{
objects_created++;
objects_alive++;
}
counter(const counter&)
{
objects_created++;
objects_alive++;
}
protected:
virtual ~counter()
{
--objects_alive;
}
static int objects_created;
static int objects_alive;
};
template <typename T> int counter<T>::objects_created( 0 );
template <typename T> int counter<T>::objects_alive( 0 );
class X : counter<X>
{
// ...
};
class Y : counter<Y>
{
// ...
};
Usage for completeness:
int main()
{
X x1;
{
X x2;
X x3;
X x4;
X x5;
Y y1;
Y y2;
} // objects gone
Y y3;
cout << "created: "
<< " X:" << counter<X>::objects_created
<< " Y:" << counter<Y>::objects_created //well done
<< endl;
cout << "alive: "
<< " X:" << counter<X>::objects_alive
<< " Y:" << counter<Y>::objects_alive
<< endl;
}
Output:
created: X:5 Y:3
alive: X:1 Y:1
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…