Object Instantiations couting using composition in c++ -


in more effective c++ meyers has described way count instantiation of objects using object counting base class (item 26). possible implement same using composition technique below . there specific advantage using private inheritance , drawbacks of using composition in case.

ps:- have reused code more effective c++ small modification.

    #ifndef countertemplate_hpp_     #define countertemplate_hpp_     #include <iostream>     #include <stdio.h>     #include <stdlib.h>      template <class beingcounted>     class counted {     public:         static int objectcount(){return numofobjects;}         counted();         counted(const counted& rhs);         ~counted(){--numofobjects;}     protected:     private:         static int numofobjects;         static int maxnumofobjects;         void init();     };      template<class beingcounted> counted<beingcounted>::counted()     {         init();     }      template<class beingcounted> counted<beingcounted>::counted(const counted& rhs)     {         init();     }      template<class beingcounted> void counted<beingcounted>::init()     {         if(numofobjects>maxnumofobjects){}         ++numofobjects;     }      class printer     {             public:         static printer* makeprinter(){return new printer;};         static printer* makeprinter(const printer& rhs);         counted<printer>& getcounterobject(){return counterobject;}         ~printer();             private:         printer(){};         counted<printer> counterobject;         printer(const printer& rhs){};     };      #endif /* countertemplate_hpp_ */ 

this question related to

of two, 1 duplicate of other. neither answers question, , i'm somehow reluctant post answer 1 of them.


private inheritance can make use of empty base class optimization:

class printer0 {     counted<printer0> counterobject;     int m; };  class printer1 : counter<printer1> {     int m; }; 

clang++ , g++ both sizeof(printer0) == 8 , sizeof(printer1) == 4.

the reason data members have have different addresses, single empty base class not need use memory in object. counterobject 1 byte large, , int aligned 4 byte, therefore printer0 looks this:

   | | x x |       |    0 1 2 3 4 5 6 7 8 9           ^~~~~~~~~ m       ^~~~ padding   ^~~~ counterobject 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -