【问题标题】:virtual inheritance and memory layout虚拟继承和内存布局
【发布时间】:2018-10-06 09:17:38
【问题描述】:
  GCC/32Bit architecture  

class B
    {
        int x,y;
    };
    class D1: public virtual B
    {
        int z;
    };
    class D2; public virtual B
    {
        int z;
    public:
    virtual void func(){}
    };

    int main() {
        B b; D1 d1; D2 d2;
        cout<<sizeof(b)<<endl;
        cout<<sizeof(d1)<<endl;
        cout<<sizeof(d2)<<endl;
        return 0;
    }  

据我了解, B有2个整数:8字节 D1:偏移到 B(B _vPtr), x,y,z => 16。 D2: B _vBase, VPTR, x, y => 16

       Ans i am getting is 8, 24, 24.
       What is the size of the class and how memory allocated for this classes. 
    How is Vptr and Vtable managed in these cases.

【问题讨论】:

    标签: inheritance virtual


    【解决方案1】:

    你用的是什么编译器?视觉工作室?海合会?铛?什么目标架构(主要是 32 位或 64 位)? 你也可以看看Size of the classes in case of virtual inheritance

    我不是在看布局,但我会说在指向父级的指针与其实际数据之间存在填充,以使数据对齐 8 字节。这意味着 4bytes + padding(4) + 8bytes of parent data + local data + padding?

    【讨论】:

    • 是否有任何其他链接可以更详细地了解上述查询。我用过 32 位和 gcc
    • shaharmike.com/cpp/vtable-part3 也对这些类型的类的成员进行了完整的探索(尽管它不只显示虚拟类的布局,而是显示完整菱形的布局,因为它是我知道的虚拟继承)。
    猜你喜欢
    • 2015-09-01
    • 2012-07-21
    • 2020-09-30
    • 2015-04-15
    • 2023-03-13
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    相关资源
    最近更新 更多