Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: How to count all instantiated objects at runtime?

I have a large framework consisting of many C++ classes. Is there a way using any tools at runtime, to trace all the C++ objects that are being constructed and currently exist?

For example, at a certain time t1, perhaps the application has objects A1, A2 and B3, but at time t2, it has A1, A4, C2 and so on?

This is a cross platform framework but I'm familiar with working in Linux, Solaris and (possibly) Mac OS X.

like image 751
nina Avatar asked Apr 28 '10 12:04

nina


1 Answers

You can inject code in the destructor and constructor of the objects that you want to count:

SomeObject::SomeObject() {
   ++globalSomeObjectCounter;
}

SomeObject::~SomeObject() {
   --globalSomeObjectCounter;
}

Don't forget to increase the counter in all constructors (copy constructors, etc.)

EDIT: In this situation one can use the curiously recurring template pattern:

template <typename T>
struct Counter
{
    Counter() {++counter;}
    virtual ~Counter() {--counter;}
    static int counter;
};
template <typename T> int Counter<T>::counter(0);

and then:

class SomeObject : public Counter<SomeObject> {
}

to automatically generate a counter for each class type.

like image 68
Andreas Brinck Avatar answered Sep 17 '22 20:09

Andreas Brinck