how to count the number of objects created in c++
pls explain with a simple example
You can count the total number of elements or some specific elements in the array using an extension method Count() method. The Count() method is an extension method of IEnumerable included in System. Linq.
Static Members Only one copy of a static member exists, regardless of how many instances of the class are created.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With