且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++对象生存期概要分析

更新时间:2023-11-13 17:39:58

这可以跟踪堆栈对堆栈对象的创建

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
}

这使用了Bartek在评论中提出的CRTP对你的问题。这使我们分别跟踪每个派生类型。它还为基类包装标准 new ,这是由派生类继承的,这允许我们跟踪堆分配。因此,我们知道创建了多少实例,以及在堆上有多少实例,我们可以推断其余实例在栈上(除非您在程序中使用对象池或其他更具异乎寻常的分配策略)。

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).