对象实例化在c ++中使用组合进行couting

时间:2014-05-31 13:01:06

标签: c++ composition private-inheritance

更有效的C ++ Meyers描述了一种使用对象计数基类来计算对象实例化的方法(第26项)。是否可以使用如下的组合技术实现相同的技术。使用私有继承是否有特定的优势,在这种情况下使用组合有什么缺点。

ps: - 我重复使用了更有效的C ++中的代码并进行了少量修改。

    #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_ */

2 个答案:

答案 0 :(得分:2)

这个问题与

有关

在这两个中,一个可能是另一个的副本。但是没有回答这个问题,而且我不愿意将答案发给其中一个。


私有继承可以使用空基类优化:

class Printer0
{
    Counted<Printer0> counterObject;
    int m;
};

class Printer1 : Counter<Printer1>
{
    int m;
};

Clang ++和g ++都说sizeof(Printer0) == 8sizeof(Printer1) == 4

原因是数据成员必须有不同的地址, 但是单个空基类不需要在对象中使用内存。 所以counterObject大一个字节,int对齐到4个字节, 因此Printer0看起来像这样:

  | | X X |       | 
  0 1 2 3 4 5 6 7 8 9
          ^~~~~~~~~ m
      ^~~~ padding
  ^~~~ counterObject

答案 1 :(得分:0)

组成迫使你“污染”#34;您的类的代码与元数据(即计数器对象)并不与其主要业务相关,在我看来,这使得代码在这种情况下的可读性降低。另请参阅@dyp答案,了解空类优化的技术方面。

相关问题