Monday 25 July 2016

c++ Static variable for object count


It is very often that you might need to count the current number of instance of this class. 


class Widget {
public:
    Widget() { ++count; }
    Widget(const Widget&) { ++count; }
    ~Widget() { --count; }
    static size_t howMany()
    { return count; }
private:
    static size_t count;
};

size_t Widget::count = 0;


Intuitively, you need a static variable in the class. However, it is very important to remember that 
static size_t count; is only a declaration and there is no memory allocated and referred to this variable. That is, we need the last line, size_t Widget::count = 0;, so that the linker knows what memory location you're referring to when you use the name.


ref:
http://www.drdobbs.com/cpp/counting-objects-in-c/184403484
http://stackoverflow.com/questions/7781188/static-variable-for-object-count-in-c-classes

No comments:

Post a Comment