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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With