且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在编译器中实现C ++虚拟继承?

更新时间:2022-10-14 23:27:05

依赖。 GCC(请参阅此问题),例如,将发出两个构造函数,一个具有调用 A(1),另一个没有。

  B1 )
B2()// no A

构建B时,版本被调用:

  B1():
A(1)
B $ b

构建C时,将调用基本版本:


$ b b
  C():
A(3)
B2()
B $ b

事实上,即使没有虚拟继承,也会抛出两个构造函数, / p>

How the compilers implement the virtual inheritance?

In the following code:

class A {
  public:
    A(int) {}
};

class B : public virtual A {
  public:
    B() : A(1) {}
};

class C : public B {
  public:
    C() : A(3), B() {}
};

Does a compiler generate two instance of B::ctor function, one without A(1) call, and one with it? So when B::constructor is called from derived class's constructor the first instance is used, otherwise the second.

It's implementation-dependent. GCC (see this question), for example, will emit two constructors, one with a call to A(1), another one without.

B1()
B2() // no A

When B is constructed, the "full" version is called:

B1():
    A(1)
    B() body

When C is constructed, the base version is called instead:

C():
    A(3)
    B2()
       B() body
    C() body

In fact, two constructors will be emitted even if there is no virtual inheritance, and they will be identical.