The purpose of this paper is to implement a practical class of C + + class counting, and to point out some C + + knowledge which is easy to be neglected in the process of implementation.
The easiest way to implement an object (instance) Count of a class, that is, how many objects exist in this class in a program run, is to use static data members. As follows:
class Widget {
public:
Widget() { ++count; }
Widget(const Widget&) { ++count; }
~Widget() { --count; }
static size_t howMany()
{ return count; }
private:
static size_t count;
};
//cpp文件中
size_t Widget::count = 0;
Note that constructors also have to increase the count, which is easy for many people to forget.
However, if you have multiple classes in your program that require instance counting, adding the code above in each class is cumbersome and error-prone. In this case, it is best to implement a universal count class. It should have features:
Easy to use: any class that needs to be counted (hereinafter referred to as the Customer class) can be used only if a few codes are added;
Efficiency: does not increase customer class size, has no effect on customer class performance;
Robust: When used by customers, it is not easy to misuse.
Here we will progressively implement and refine this generic counting class.
class Counter {
public:
Counter() { ++count; }
Counter(const Counter&) { ++count; }
~Counter() { --count; }
static size_t howMany()
{ return count; }
private:
static size_t count;
};
// This still goes in an implementation file
size_t Counter::count = 0;
Does the above counter class correctly complete the count? For example: The Widget class uses it for instance counting:
// embed a Counter to count objects
class Widget {
public:
..... // all the usual public
// Widget stuff
static size_t howMany()
{ return Counter::howMany(); }
private:
..... // all the usual private
// Widget stuff
Counter c;
};
//or:
// inherit from Counter to count objects
class Widget: public Counter {
..... // all the usual public
// Widget stuff
private:
..... // all the usual private
// Widget stuff
};