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

前端 未结 6 1460
一个人的身影
一个人的身影 2020-12-13 21:14

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

pls explain with a simple example

6条回答
  •  我在风中等你
    2020-12-13 21:54

    update on code as opposed to "stefanB" solution, some variables are in protected access mode and will not be accessible.

    template 
        struct counter
        {
            counter()
            {
                std::cout << "object created"<< endl;
                this->objects_created++;
                this->objects_alive++;
            }
    
            counter(const counter& test)
            {
                std::cout << "object created:" << test << endl;
                 this->objects_created++;
                 this->objects_alive++;
            }
    
            static int getObjectsAlive(){
                return objects_alive;
            }
    
            static int getObjectsCreated(){
                return objects_created;
            }
    
    
        protected:
            virtual ~counter()
            {
                std::cout << "object destroyed"<< endl;
                --objects_alive;
            }
            static int objects_created;
            static int objects_alive;
        };
        template  int counter::objects_created( 0 );
        template  int counter::objects_alive( 0 );
    
        class X : counter
        {
            // ...
        };
    
        class Y : counter
        {
            // ...
        };
        
        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::getObjectsCreated()
             << " Y:" << counter::getObjectsCreated()  //well done
             << endl;
    
        cout << "alive: "
             << " X:" << counter::getObjectsAlive()
             << " Y:" << counter::getObjectsAlive()
             << endl;
            }
    

提交回复
热议问题