Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
723 views
in Technique[技术] by (71.8m points)

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

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

pls explain with a simple example

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...