How do I find the number of objects that are alive in C++?
I want to find the objects of a class that are currently alive in C++. Please tell me a solution for this. Also, please correct if my logic is wrong!
- Declare a global variable.
- Increment it during the constructor invocation.
- Decrement during dest开发者_如何学Cructor invocation.
Thanks in advance.
Sanjeev
keep a static variable in your class as count. Global variables are not good practice.
Your logic is correct except for one thing: don't make it a global variable; it is untidy and there is the danger that a bug in some other code might modify it. Instead make it a private static member variable of the class.
Take a look at the curiously recurring template pattern, it is great for this sort of thing and the example in wikipedia shows how to use it for an object counter.
template <typename T>
struct counter
{
counter()
{
++objects_created;
++objects_alive;
}
virtual ~counter()
{
--objects_alive;
}
// if you are using multiple threads, these need to be protected
// with interlocked operations as appropriate per your compiler + platform
static int objects_created;
static int objects_alive;
};
template <typename T> int counter<T>::objects_created( 0 );
template <typename T> int counter<T>::objects_alive( 0 );
class X : counter<X>
{
// ...
};
class Y : counter<Y>
{
// ...
};
It's impossible in C++. Tracking constructor and destructor does not guarantee the accuracy: how do you prevent a memory copy like this:
memcpy(buf, &instance, sizeof(T));
T* anotherInstance = (T*)buf;
精彩评论