C++虚拟继承内存布局

Dom*_*ino 5 c++ oop inheritance multiple-inheritance virtual-inheritance

虚拟继承内存布局

我试图通过虚拟继承和vTables/vPtrs完全理解内存中发生的事情,什么不是.

我有两个我编写的代码示例,我完全理解它们的工作原理,但我只想确保在脑海中对对象内存布局有正确的想法.

以下是图片中的两个示例,我只想知道我对所涉及的内存布局的想法是否正确.

例1:

class Top { public: int a;  };
class Left : public virtual Top {  public: int b; };
class Right : public virtual Top { public: int c; };
class Bottom : public Left, public Right { public:  int d; };
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

例2:

与上述相同,但有:

class Right : public virtual Top {
public:
    int c;
    int a;  // <======= added this
};
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Chr*_*phe 1

C++ 标准没有对对象布局做太多说明。虚拟函数表(vtable)和虚拟基指针甚至不是标准的一部分。所以问题和答案只能说明可能的实现。

快速查看您的绘图似乎显示了正确的布局。

您可能对这些进一步的参考资料感兴趣:

  • 考虑多重继承一篇有关多重继承和虚拟继承情况下布局的 ddj 文章很有用。

  • 微软专利描述了 vfptr(虚拟函数表,又名 vtable)和 vbptr(虚拟基指针)的使用。

编辑:Bottom 继承Right::a还是Left::a

在你的测试2中,RightLeft共享同一个共同的父对象TopTop因此中只有一个子对象Bottom,因此也只有一个且相同的Top::a

有趣的是,您在测试 2 中引入了a中的一名成员Right。这是一个aa继承自不同的Top。它是一个独特的成员,只是“巧合”地与另一个成员同名。因此,如果您a通过访问RightRight::a则会隐藏Top::a(顺便说一下Bottom::Top::a,也是Right::Top::a、 、Left::Top::a)。在本例中,bottom.a 表示 Right::a,不是因为对象布局,而是因为名称查找(和隐藏)规则。这与实现无关:它是标准的且可移植的。

这里有一个测试 2 的变体来演示这种情况:

int main() {
    Bottom bottom; 
    bottom.a = 7; 
    cout << bottom.Top::a << endl << bottom.Left::Top::a << endl;
    cout << bottom.Right::Top::a << endl << bottom.Left::a << endl;
    cout << bottom.Right::a << endl <<endl;
    bottom.Right::a = 4; 
    bottom.Left::a = 3; 
    cout << bottom.Top::a << endl << bottom.Left::Top::a << endl;
    cout << bottom.Right::Top::a << endl << bottom.Left::a << endl;
    cout << bottom.Right::a << endl <<endl;

    cout << "And the addresses are: " << endl; 
    cout << " Bottom:       " << (void*)&bottom << endl; 
    cout << " Top:          " << (void*)static_cast<Top*>(&bottom) << endl;
    cout << " Left:         " << (void*)static_cast<Left*>(&bottom) << endl;
    cout << " Right:        " << (void*)static_cast<Right*>(&bottom) << endl;
    cout << " Top::a:       " << (void*)&bottom.Top::a << endl;
    cout << " Left::Top::a: " << (void*)&bottom.Left::Top::a << endl;
    cout << " Right::Top::a:" << (void*)&bottom.Right::Top::a << endl;
    cout << " Left::a:      " << (void*)&bottom.Left::a << endl;
    cout << " Rigth::a:     " << (void*)&bottom.Right::a << endl;
}; 
Run Code Online (Sandbox Code Playgroud)