Simplest way to count instances of an object

后端 未结 8 1911
时光取名叫无心
时光取名叫无心 2021-01-01 17:42

I would like to know the exact number of instances of certain objects allocated at certain point of execution. Mostly for hunting possible memory leaks(I mostly use RAII, al

8条回答
  •  攒了一身酷
    2021-01-01 18:18

    you can apply this approach

    #ifdef DEBUG
    
    class ObjectCount {
        static int count;
      protected:
        ObjectCount() {
            count++;
        }
      public:
        void static showCount() {
            cout << count;
        }
    };
    
    int ObjectCount::count = 0;
    
    
    class Employee : public ObjectCount {
    #else
    class Employee {
    #endif
      public:
        Employee(){}
        Employee(const Employee & emp) {
    
        }
    };
    

    at DEBUG mode, invoking of ObjectCount::showCount() method will return count of object(s) created.

提交回复
热议问题