Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

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



Application Security Testing: An Integral Part of DevOps

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
 static int count;
 A() { ++count;}
 A(const A& rhs) { ++count;}
 ~A() {--count;}
 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.



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