how to count the number of objects created in c++

前端 未结 6 1459
一个人的身影
一个人的身影 2020-12-13 21:14

how to count the number of objects created in c++

pls explain with a simple example

6条回答
  •  臣服心动
    2020-12-13 21:55

    You could create a counter variable into the public: of your class (assuming here you're talking about counting objects from a class you created)

    class Widget {
    public:
        Widget() { ++count; }
        Widget(const Widget&) { ++count; }
        ~Widget() { --count; }
    
        static size_t howMany()
        { return count; }
    
    private:
        static size_t count;
    };
    // obligatory definition of count. This
    // goes in an implementation file
    size_t Widget::count = 0;
    

    Taken from ddj.com

提交回复
热议问题