Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to count the number of objects created in c++

Tags:

c++

how to count the number of objects created in c++

pls explain with a simple example

like image 971
Arunachalam Avatar asked Dec 18 '09 06:12

Arunachalam


People also ask

How do I count objects in C#?

You can count the total number of elements or some specific elements in the array using an extension method Count() method. The Count() method is an extension method of IEnumerable included in System. Linq.

How many copies of a static member of a class are created?

Static Members Only one copy of a static member exists, regardless of how many instances of the class are created.


1 Answers

Create template class with a static counter.

Each object in your application would then extend this template class.

When constructor is called increment static count (static variable is per class - shared by all objects of that class).

For example see Object Counter using Curiously recurring template pattern:

 template <typename T>
    struct counter
    {
        counter()
        {
            objects_created++;
            objects_alive++;
        }

        counter(const counter&)
        {
             objects_created++;
             objects_alive++;
        }   

    protected:
        virtual ~counter()
        {
            --objects_alive;
        }
        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>
    {
        // ...
    };

Usage for completeness:

    int main()
    {
        X x1;

        {
            X x2;
            X x3;
            X x4;
            X x5;
            Y y1;
            Y y2;
        }   // objects gone

        Y y3;

        cout << "created: "
             << " X:" << counter<X>::objects_created
             << " Y:" << counter<Y>::objects_created  //well done
             << endl;

        cout << "alive: "
             << " X:" << counter<X>::objects_alive
             << " Y:" << counter<Y>::objects_alive
             << endl;
    }

Output:

created:  X:5 Y:3
alive:  X:1 Y:1
like image 165
stefanB Avatar answered Oct 26 '22 08:10

stefanB