BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #83180同步于 2014/10/8
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

虚继承问题

ylewxh
2014/10/8镜像同步6 回复
class A {int a;}; class B : virtual A {int b;}; class C : virtual A {int c;}; class D : B, C {}; 这时取sizeof A 4 B 12 C 12 D 20 如果D是 class D : virtual B, C {}; 取sizeof D 20 如果D是 class D : virtual B, virtual C {}; 取sizeof D 24 为啥是24啊,求大神解答[ema0]
订阅后,新回复会通过你的通知中心匿名送达。
6 条回复
ashjn2011机器人#1 · 2014/10/8
摘自《Inside the C++ Object Model》: In the case of virtual inheritance, only a single occurrence of the base class is maintained (called a subobject) regardless of how many times the class is derived from within the inheritance chain. iostream, for example, contains only a single instance of the virtual ios base class. How might a derived class internally model its base class instance? In a simple base class object model, each base class might be assigned a slot within the derived class object. Each slot holds the address of the base class subobject. The primary drawback to this scheme is the space and access-time overhead of the indirection. A benefit is that the size of the class object is unaffected by changes in the size of its associated base classes. Alternatively, one can imagine a base table model. Here, a base class table is generated for which each slot contains the address of an associated base class, much as the virtual table holds the address of each virtual function. Each class object contains a bptr initialized to address its base class table. The primary drawback to this strategy, of course, is both the space and access-time overhead of the indirection. One benefit is a uniform representation of inheritance within each class object. Each class object would contain a base table pointer at some fixed location regardless of the size or number of its base classes. A second benefit would be the ability to grow, shrink, or otherwise modify the base class table without changing the size of the class objects themselves. VC编译器就是按照第一种实现的,所以有两个bptr, 听说g++是按照第二种方法实现的
ylewxh机器人#2 · 2014/10/8
【 在 ashjn2011 的大作中提到: 】 : 摘自《Inside the C++ Object Model》: : In the case of virtual inheritance, only a single occurrence of the base class is maintained (called a subobject) : regardless of how many times the class is derived from within the inheritance chain. iostream, for example, : ................... 谢谢解答。我使用的是vs,一开始我也以为有2个vbptr,所以做了以下实验: class A { int a; }; class B { int b; }; class C :virtual A, virtual B { }; 结果 sizeof(C) 的结果是 12, 也就是只有1个vbptr,这个很奇怪啊。。
ylewxh机器人#3 · 2014/10/9
顶一下
FromMars机器人#4 · 2014/10/9
每年这个时候都会有这种问题
ajin机器人#5 · 2014/10/9
跟编译器的关系太大了,详细的请看《深度搜索C++对象模型》侯捷译,page83-88.
byr10th机器人#6 · 2014/10/9
因为B和C共用同一个指针指向同一个基类A,所以不是28,而是24...