Meyers在更有效的C ++中描述了一种使用对象计数基类(项目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_ */
这个问题与
在这两个中,一个可能是另一个的重复。但是没有一个回答这个问题,而且我不愿将我的回答发布给其中一个。
私有继承可以利用空基类优化:
class Printer0
{
Counted<Printer0> counterObject;
int m;
};
class Printer1 : Counter<Printer1>
{
int m;
};
Clang ++和g ++都说sizeof(Printer0) == 8
和sizeof(Printer1) == 4
。
原因是数据成员必须具有不同的地址,但是单个空基类不需要用完对象中的内存。所以counterObject
是一个字节大,并int
与4个字节对齐,因此Printer0
如下所示:
| | XX | | 0 1 2 3 4 5 6 7 8 9 ^ ~~~~~~~~ m ^ ~~~填充 ^ ~~~ counterObject
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句