Simplest way to count instances of an object

后端 未结 8 1930
时光取名叫无心
时光取名叫无心 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:15

    Have a "counted object" class that does the proper reference counting in its constructor(s) and destructor, then derive your objects that you want to track from it. You can then use the curiously recurring template pattern to get distinct counts for any object types you wish to track.

    // warning: pseudo code
    
    template 
    class CountedObj
    {
    public:
       CountedObj() {++total_;}
       CountedObj(const CountedObj& obj) {if(this != &obj) ++total_;}
       ~CountedObj() {--total_;}
    
       static size_t OustandingObjects() {return total_;}
    
    private:
       static size_t total_;
    };
    
    class MyClass : private CountedObj
    {};
    

提交回复
热议问题