C++ object lifetime profiling

▼魔方 西西 提交于 2019-12-04 16:57:39

This can track stack vs. heap object creations

#include <iostream>

template <class CRTP>
struct AllocationTracker
{
    AllocationTracker()
    {
        ++totalCreated;
    }

    void* operator new(size_t sz)
    {
        ++heapCreated;
        return ::operator new(sz);
    }

    static int totalCreated;
    static int heapCreated;
};

template <class CRTP>
int AllocationTracker<CRTP>::totalCreated;
template <class CRTP>
int AllocationTracker<CRTP>::heapCreated;

class Derived : public AllocationTracker<Derived>
{
};

int main()
{
    using namespace std;
    cout << Derived::heapCreated << "/" << Derived::totalCreated << endl; // 0/0
    Derived dStack;
    cout << Derived::heapCreated << "/" << Derived::totalCreated << endl; // 0/1
    Derived* dHeap = new Derived;
    cout << Derived::heapCreated << "/" << Derived::totalCreated << endl; // 1/2
}

This uses the CRTP that Bartek brought up in the comments on your question. This lets us track each derived type separately. It also wraps the standard new for the base class, which is inherited by derived classes, which allows us to track heap allocations. So we know how many instances are created, and how many on the heap, and we can infer that the rest were on the stack (unless you're using object pools or some other more exotic allocation strategies in your program).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!