虚继承中direct base是如何构造的?

How direct base is constructed in virtual inheritance?

在下面的代码中,我试图创建一个Leaf对象obj来查看多层继承中的构造函数顺序,但我发现obj和构造函数的结构在这种情况下调用有点奇怪。

#include<iostream>
using namespace std;
class Base1 { 
public:
    Base1(void) { 
        cout << "class Base1" << endl; 
    } 
}; 
class Base2 {
public: 
    Base2(void) { 
        cout << "class Base2" << endl; }
};
class Level1 : public Base2, virtual public Base1
{
public:
    Level1(void)
    {
        cout << "class Level1" << endl;
    }
};

class Level2 : public Base2, virtual public Base1
{
public:
    Level2(void)
    {
        cout << "class Level2" << endl;
    }
};

class Leaf :virtual public Level2, virtual public Level1
{
public:
    Leaf(void)
    {
        cout << "class Leaf" << endl;
    }
};


int main(void)
{
    Leaf obj;
    return 0;
}

输出显示构造函数调用:

class Base1
class Base2
clase Level2
class Base2
class Level1
class Leaf

但是程序最后obj的结构其实是:

obj
--Level2
----Base2
----Base1
--Level1
----Base2
----Base1
--Base1

我知道objBase1是虚继承的,但是在obj的构造过程中,Level2Level1也是需要的构造,导致每个结构中的 Base1 。但是整个构建过程只调用了一次Base1构造函数。我无法解释这一点。这是否意味着 Level2 中的 Base1obj 中的 Level1 与直接属于 objBase1 共享相同的数据?

But the whole construction process only calls Base1 constructor once. I cannot explain this.

解释是Base1是层次结构中所有classes的虚拟基。这正是虚拟基地的含义及其用途:共享公共基地 class 个实例。

引用自cppreference

For each distinct base class that is specified virtual, the most derived object contains only one base class subobject of that type, even if the class appears many times in the inheritance hierarchy (as long as it is inherited virtual every time).

All virtual base subobjects are initialized before any non-virtual base subobject, so only the most derived class calls the constructors of the virtual bases in its member initializer list:

考虑到虚拟继承,你的结构图可以认为是这样的:

obj
--Level2
----Base2
----+-------Base1
--Level1   / /
----Base2 / /
----+----/ /
--+-------/

Does this mean the Base1 in Level2 and Level1 inside obj shares the same data with Base1 that directly belongs to obj?

是的。在 obj.

的整个结构中只有一个 Base1 实例

Does this mean the Base1 in Level2 and Level1 inside obj shares the same data with Base1 that directly belongs to obj?

是的,Base1 只有一个子对象,Level2Level1 的基础子对象在 class Leaf 中共享。

这是标准示例的解释,$10.1/6 Multiple base classes [class.mi](强调我的)

For another example,

class V { /* ... */ };
class A : virtual public V { /* ... */ };
class B : virtual public V { /* ... */ };
class C : public A, public B { /* ... */ };

for an object c of class type C, a single subobject of type V is shared by every base subobject of c that has a virtual base class of type V. Given the class C defined above, an object of class C will have one subobject of class V, as shown below.