Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...