1s2a3n4j5e6e7v
1s2a3n4j5e6e7v

Reputation: 1259

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!

Thanks in advance.

Sanjeev

Upvotes: 1

Views: 446

Answers (4)

Rick
Rick

Reputation: 3353

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>
{
    // ...
};

Upvotes: 1

Codism
Codism

Reputation: 6224

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;

Upvotes: 0

Beta
Beta

Reputation: 99094

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.

Upvotes: 6

Samrat Patil
Samrat Patil

Reputation: 798

keep a static variable in your class as count. Global variables are not good practice.

Upvotes: 6

Related Questions