Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Intermediate
Aug 11, 2000

Counting "Live" Instances of a Class

Counting the number of object instances of a certain class can be necessary in debugging and performance tuning. To do that, declare a static data member as a counter, and have the constructor and copy constructor increment it and the destructor decrement it. Finally, add a static member function that returns the current instance count:

 
class A
{
private:
 static int count;
public:
 A() { ++count;}
 A(const A& rhs) { ++count;}
 ~A() {--count;}
public:
 static int get_count() {return count;}
};

int A::count; //definition of static member

Because static members are automatically zero-initialized, you can call this function and get the correct results even if there's not a single instance of that class at that time:

 
int main()
{
 int n = A::get_count(); // 0
 A a;
 n = A::get_count(); // 1
 A * p = new A(a);
 n = A::get_count(); // 2
 delete p; 
 n = A::get_count(); // 1
}
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date