备案查询站长之家,搭建网页游戏服务器,网站找不到首页,做海报 画册的素材网站相关系列文章 C惯用法之Pimpl C惯用法之CRTP(奇异递归模板模式) C之std::tuple(二) : 揭秘底层实现原理 目录
1.空类
2.空基类优化
3.内存布局原则
4.实例分析
5.总结 1.空类 C 中每个对象的实例都可以通过取地址运算符获取其在内存布局中的开始位置#xff0c;因此每个类… 相关系列文章 C惯用法之Pimpl C惯用法之CRTP(奇异递归模板模式) C之std::tuple(二) : 揭秘底层实现原理 目录
1.空类
2.空基类优化
3.内存布局原则
4.实例分析
5.总结 1.空类 C 中每个对象的实例都可以通过取地址运算符获取其在内存布局中的开始位置因此每个类对象至少需要占用一个字节的空间。空类是指不包含非静态数据成员的类但是可以包含成员函数及静态成员。C 中空类的大小是 1 字节。
class CEmpty1
{};
class CEmpty2
{static int i;
};class CEmpty3
{
public:void func1() {};void func2() {};
};int main()
{cout CEmpty1大小: sizeof(CEmpty1) endl; //输出: 1cout CEmpty2大小: sizeof(CEmpty2) endl; //输出: 1cout CEmpty3大小: sizeof(CEmpty3) endl; //输出: 1return 0;
}
结果是1它是空的怎么不是0呢
因为空类同样可以被实例化每个实例在内存中都有一个独一无二的地址为了达到这个目的编译器往往会给一个空类隐含的加一个字节这样空类在实例化后在内存得到了独一无二的地址所以上述大小为1。
2.空基类优化 注空基类优化可简称为EBO empty base optimization或者 EBCO empty base class optimization 在没有歧义的情况下C 允许空基类的子对象大小为 0。
一般来讲对一个既有类进行扩展时除非有更好的理由采用继承有虚函数需要重新实现、有受保护的私有成员需要访问否则采用组合的方式进行扩展。
现对比一下两种模式第一种类中把空类做为成员变量使用然后通过这个来获得被包含类的功能如
class CEmpty {};
class CDerived1 {CEmpty m_base;int m_i;//other function...
};
另一种直接采用继承的方式来获得基类的成员函数及其他功能等等。如
class CDerived2 : public CEmpty {int m_i;//other function...
};
接下来做个测试
std::coutsizeof(CDerived1)std::endl; //输出: 8
std::coutsizeof(CDerived2)std::endl; //输出4
第一种本来只占1字节会因为字节对齐进行扩充到4的倍数最后就是8字节。 对比这两个发现第二种通过继承方式来获得基类的功能并没有产生额外大小的优化称之为EBO(空基类优化)。
3.内存布局原则 C的设计者不允许类的大小为0其原因有很多比如由它们构成的数组其大小必然也是0这会导致指针运算中普遍使用的性质失效。比如假设类型ZeroSizedT的大小为0则下面的操作会出现错误
ZeroSizedT z[10];
auto v z[9] - z[2]; // 计算指针/地址之间的距离 正常情况下上例中的差值是通过将两个地址之间的字节数除以指针指向的类型的大小得出来的但是它们的大小是0时该关系就显然就不成立了。 尽管C中没有大小为0的类型但是C规定当空类作为基类时不需要为其分配空间前提是这样做不会导致它被分配到与其他对象或者同类型的子对象相同的地址上。看个例子
#include iostream
class EmptyClass{using Bool bool; //类型别名成员不会让一个类成为非空类
};
class EmptyFoo : public EmptyClass{
};
class EmptyThree : public EmptyFoo{
};
int main(){std::cout sizeof(EmptyClass) std::endl; //输出1std::cout sizeof(EmptyFoo) std::endl; //输出1std::cout sizeof(EmptyThree ) std::endl; //输出1
}
如果编译器支持空基类优化上面程序的所有输出结果相同但是均不为0。也就是说在类EmptyFoo 中的类 EmptyClass没有分配空间 。 如下图
如果不支持空基类优化上面程序的输出结果不同。布局如下图
再看个例子
#include iostream
class EmptyClass{using Bool bool; //类型别名成员不会让一个类成为非空类
};
class EmptyFoo : public EmptyClass{
};
class NoEmpty :public EmptyClass, public EmptyFoo{
};
int main(){std::cout sizeof(EmptyClass) std::endl; //输出1std::cout sizeof(EmptyFoo) std::endl; //输出1std::cout sizeof(NoEmpty) std::endl; //输出2
} NoEmpty 为什么不为空类呢这是因为NoEmpty 的基类EmptyClass和EmptyFoo 不能分配到同一地址空间否则EmptyFoo 的基类EmptyClass和NoEmpty 的EmptyClass会撞到同一地址空间上。换句话说两个相同类型的子对象偏移量相同这是C布局规则不允许的 对空基类优化进行限制的根据原因在于我们需要能比较两个指针是否指向同一对象。由于指针几乎总是用地址内部表示所以我们必须保证两个不同的地址即两个不同的指针对应两个不同的对象。 这个限制也许看起来不是非常重要。然而在实践中经常会遇到相关问题因为许多类往往继承自某些空类的一个小集合而这些空类又往往定义了一些共同的类型别名。当这样的类的两个子对象被用在同一个完整对象中时优化就会被阻止。 就算有此限制EBCO仍是模板库的一个重要优化因为有些技巧要依赖于某些基类的引入而引入这些基类只是为了引入新的类型别名或者在不增加新数据的情况提供额外功能。
4.实例分析
std::tuple实际也应用了空基类优化,如
struct Base1 {}; // 空类
struct Base2 {}; // 空类
struct Base3 {}; // 空类int main()
{std::cout sizeof(std::tupleBase1, Base2, Base3) , sizeof(std::tupleBase1, Base2, Base3, int);
}
// 输出为1,4
本节介绍std::tuple中如何应用EBO本文以mingw平台上的实现为例进行讲解。
tuple的模板参数可以支持接收任意类型熟悉可变模板参数的同学可以快速实现如下代码
templatetypename ...Args
struct Tuple;
template
struct Tuple {
};templatetypename Head, typename ...Tail
struct TupleHead, Tail... {Head h;TupleTail... t;
};
此时模板参数类型为空类时存在内存浪费下一步应用EBO优化得到
templatetypename ...Args
struct Tuple;
template
struct Tuple {
};templatetypename Head, typename ...Tail
struct TupleHead, Tail... : private Head, TupleTail... {
};
但Head可能为int或者final类等不可继承类型因此引入TupleEle
templatetypename T, bool std::is_classT::value !std::is_finalT::value
struct TupleEle;templatetypename T
struct TupleEle T, false {T value;T Get() { return value; }
};templatetypename T
struct TupleEle T, true : private T {T Get() { return *this; }
};templatetypename ...Args
struct Tuple;template
struct Tuple {
};templatetypename Head, typename ...Tail
struct TupleHead, Tail...: private TupleEleHead, private TupleTail... {
};
此时如果送入重复类型则重复继承了TupleElexxx导致 派生类转换到基类存在歧义因此进一步修改为
templatesize_t index, typename T, bool std::is_classT::value !std::is_finalT::value
struct TupleEle;templatesize_t index, typename T
struct TupleEle index, T, false {T value;T Get() { return value; }
};templatesize_t index, typename T
struct TupleEle index, T, true : private T {T Get() { return *this; }
};templatetypename ...Args
struct Tuple;
template
struct Tuple {
};templatetypename Head, typename ...Tail
struct TupleHead, Tail...: private TupleElesizeof...(Tail), Head, private TupleTail... {
};
得益于EBO继承关系在实现Getxxx(tuple)利用模板参数推导可以在常量时间内获取对应元素补充Get之后的完整代码如下
templatesize_t index, typename T, bool std::is_classT::value !std::is_finalT::value
struct TupleEle;templatesize_t index, typename T
struct TupleEle index, T, false {templatetypename UTupleEle(U u) : value(std::forwardU(u)) {};T Get() { return value; }
private:T value;
};templatesize_t index, typename T
struct TupleEle index, T, true : private T {templatetypename UTupleEle(U u) : T(std::forwardU(u)) {};T Get() { return *this; }
};templatetypename ...Args
struct Tuple;
template
struct Tuple {
};templatetypename Head, typename ...Tail
struct TupleHead, Tail...: TupleElesizeof...(Tail), Head, private TupleTail... {templatetypename H, typename ...RestTuple(H h, Rest...rest) : TupleElesizeof...(Tail), Head(std::forwardH(h)),TupleTail...(std::forwardRest(rest)...){}templatesize_t index, typename ...Tsfriend decltype(auto) Get(TupleTs... t);
};templatesize_t index, typename T
T GetIndex(TupleEleindex, T te) { return te.Get(); }templatesize_t index, typename ...Ts
decltype(auto) Get(TupleTs... t) { return GetIndexsizeof...(Ts) - index -1(t); }
在GetIndex调用时通过模板参数推导index确定推导出对应T
std::tuple在vs2019平台上的实现跟mingw上的实现还是有些差异具体的差异可以查看我的另外一篇博客 C之std::tuple(二) : 揭秘底层实现原理-CSDN博客 5.总结 为了减少空基类对象的内存占用C编译器引入了空基类优化。当一个类作为基类被继承时如果这个基类是空的编译器会将派生类对象的地址指向基类对象的地址从而实现对基类对象的共享。这样一来派生类对象就可以共享基类对象的内存空间避免了额外的内存开销。 空基类优化可以提高程序的性能和内存利用率特别是在涉及大量继承关系和多重继承的情况下。通过减少空基类对象的内存占用可以降低内存开销并提高程序的运行效率。 需要注意的是不是所有的编译器都支持空基类优化技术。因此在使用该技术时需要检 查目标编译器是否支持该优化并确保代码符合优化的要求。
参考空基类优化 - cppreference.com 文章转载自: http://www.morning.wnzgm.cn.gov.cn.wnzgm.cn http://www.morning.hmwjk.cn.gov.cn.hmwjk.cn http://www.morning.tkyxl.cn.gov.cn.tkyxl.cn http://www.morning.mkrqh.cn.gov.cn.mkrqh.cn http://www.morning.nxnrt.cn.gov.cn.nxnrt.cn http://www.morning.rwlsr.cn.gov.cn.rwlsr.cn http://www.morning.ndngj.cn.gov.cn.ndngj.cn http://www.morning.srmdr.cn.gov.cn.srmdr.cn http://www.morning.bpmtj.cn.gov.cn.bpmtj.cn http://www.morning.lbssg.cn.gov.cn.lbssg.cn http://www.morning.xxfxxf.cn.gov.cn.xxfxxf.cn http://www.morning.zlkps.cn.gov.cn.zlkps.cn http://www.morning.zxrtt.cn.gov.cn.zxrtt.cn http://www.morning.smxyw.cn.gov.cn.smxyw.cn http://www.morning.pffx.cn.gov.cn.pffx.cn http://www.morning.tlbhq.cn.gov.cn.tlbhq.cn http://www.morning.wkrkb.cn.gov.cn.wkrkb.cn http://www.morning.kpbgp.cn.gov.cn.kpbgp.cn http://www.morning.lffrh.cn.gov.cn.lffrh.cn http://www.morning.krywy.cn.gov.cn.krywy.cn http://www.morning.flxgx.cn.gov.cn.flxgx.cn http://www.morning.lffrh.cn.gov.cn.lffrh.cn http://www.morning.sxjmz.cn.gov.cn.sxjmz.cn http://www.morning.ljjmr.cn.gov.cn.ljjmr.cn http://www.morning.zlchy.cn.gov.cn.zlchy.cn http://www.morning.jpnfm.cn.gov.cn.jpnfm.cn http://www.morning.qhvah.cn.gov.cn.qhvah.cn http://www.morning.ryjqh.cn.gov.cn.ryjqh.cn http://www.morning.smygl.cn.gov.cn.smygl.cn http://www.morning.qxkjy.cn.gov.cn.qxkjy.cn http://www.morning.xnhnl.cn.gov.cn.xnhnl.cn http://www.morning.ccyns.cn.gov.cn.ccyns.cn http://www.morning.lrprj.cn.gov.cn.lrprj.cn http://www.morning.zpyxl.cn.gov.cn.zpyxl.cn http://www.morning.zyrp.cn.gov.cn.zyrp.cn http://www.morning.dwmtk.cn.gov.cn.dwmtk.cn http://www.morning.ylpl.cn.gov.cn.ylpl.cn http://www.morning.symgk.cn.gov.cn.symgk.cn http://www.morning.nlcw.cn.gov.cn.nlcw.cn http://www.morning.qjldz.cn.gov.cn.qjldz.cn http://www.morning.txzqf.cn.gov.cn.txzqf.cn http://www.morning.tkrdg.cn.gov.cn.tkrdg.cn http://www.morning.wmnpm.cn.gov.cn.wmnpm.cn http://www.morning.mgskc.cn.gov.cn.mgskc.cn http://www.morning.dpdr.cn.gov.cn.dpdr.cn http://www.morning.thmlt.cn.gov.cn.thmlt.cn http://www.morning.mswkd.cn.gov.cn.mswkd.cn http://www.morning.sgbk.cn.gov.cn.sgbk.cn http://www.morning.qbzfp.cn.gov.cn.qbzfp.cn http://www.morning.poapal.com.gov.cn.poapal.com http://www.morning.bflws.cn.gov.cn.bflws.cn http://www.morning.rfyff.cn.gov.cn.rfyff.cn http://www.morning.ssxlt.cn.gov.cn.ssxlt.cn http://www.morning.xpzkr.cn.gov.cn.xpzkr.cn http://www.morning.xswrb.cn.gov.cn.xswrb.cn http://www.morning.tqdlk.cn.gov.cn.tqdlk.cn http://www.morning.gqjzp.cn.gov.cn.gqjzp.cn http://www.morning.sbkb.cn.gov.cn.sbkb.cn http://www.morning.gnfkl.cn.gov.cn.gnfkl.cn http://www.morning.lfdmf.cn.gov.cn.lfdmf.cn http://www.morning.csdgt.cn.gov.cn.csdgt.cn http://www.morning.kmjbs.cn.gov.cn.kmjbs.cn http://www.morning.rqsnl.cn.gov.cn.rqsnl.cn http://www.morning.qtnmp.cn.gov.cn.qtnmp.cn http://www.morning.junmap.com.gov.cn.junmap.com http://www.morning.hqllj.cn.gov.cn.hqllj.cn http://www.morning.dndjx.cn.gov.cn.dndjx.cn http://www.morning.jfmjq.cn.gov.cn.jfmjq.cn http://www.morning.gwmny.cn.gov.cn.gwmny.cn http://www.morning.fxzlg.cn.gov.cn.fxzlg.cn http://www.morning.yrnyz.cn.gov.cn.yrnyz.cn http://www.morning.blzrj.cn.gov.cn.blzrj.cn http://www.morning.xgjhy.cn.gov.cn.xgjhy.cn http://www.morning.bsrcr.cn.gov.cn.bsrcr.cn http://www.morning.qxmys.cn.gov.cn.qxmys.cn http://www.morning.tnyanzou.com.gov.cn.tnyanzou.com http://www.morning.tpbhf.cn.gov.cn.tpbhf.cn http://www.morning.ffptd.cn.gov.cn.ffptd.cn http://www.morning.zqdhr.cn.gov.cn.zqdhr.cn http://www.morning.rlwcs.cn.gov.cn.rlwcs.cn