Simplest way to count instances of an object

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

    My approach, which outputs leakage count to Debug Output (via the DebugPrint function implemented in our code base, replace that call with your own...)

    #include  
    #include 
    class CountedObjImpl
    {
    public:
            CountedObjImpl(const char* className) : mClassName(className) {}
            ~CountedObjImpl()
            {
                    DebugPrint(_T("**##** Leakage count for %hs: %Iu\n"), mClassName.c_str(), mInstanceCount);
            }
            size_t& GetCounter() 
            {
                    return mInstanceCount;
            }
    
    private:
            size_t mInstanceCount = 0;
            std::string mClassName;
    };
    
    template 
    class CountedObj
    {
    public:
            CountedObj() { GetCounter()++; }
            CountedObj(const CountedObj& obj) { GetCounter()++; }
            ~CountedObj() { GetCounter()--; }
    
            static size_t OustandingObjects() { return GetCounter(); }
    
    private:
            size_t& GetCounter()
            {
                    static CountedObjImpl mCountedObjImpl(typeid(Obj).name());
                    return mCountedObjImpl.GetCounter();
            }
    };
    

    Example usage:

    class PostLoadInfoPostLoadCB : public PostLoadCallback, private CountedObj
    

提交回复
热议问题