当调用非虚拟基本方法时,在C ++中有虚拟继承的惩罚/成本吗? [英] Is there any penalty/cost of virtual inheritance in C++, when calling non-virtual base method?

查看:176
本文介绍了当调用非虚拟基本方法时,在C ++中有虚拟继承的惩罚/成本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们从其基类调用一个常规函数成员时,在C ++中使用虚拟继承在编译代码中是否有运行时损失?示例代码:

Does using virtual inheritance in C++ have a runtime penalty in compiled code, when we call a regular function member from its base class? Sample code:

class A {
    public:
        void foo(void) {}
};
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {};

// ...

D bar;
bar.foo ();


推荐答案

可能有,函数,并且编译器不能绝对确定指针或引用指向或引用的对象的类型。例如,考虑:

There may be, yes, if you call the member function via a pointer or reference and the compiler can't determine with absolute certainty what type of object that pointer or reference points or refers to. For example, consider:

void f(B* p) { p->foo(); }

void g()
{
    D bar;
    f(&bar);
}

假设调用 f 未内联,编译器需要生成代码以查找 A 虚拟基类子对象的位置,以调用 foo 。通常这个查找包括检查vptr / vtable。

Assuming the call to f is not inlined, the compiler needs to generate code to find the location of the A virtual base class subobject in order to call foo. Usually this lookup involves checking the vptr/vtable.

如果编译器知道你调用函数的对象的类型,示例),应该没有开销,因为函数调用可以静态(在编译时)调度。在你的例子中, bar 的动态类型被称为 D (它不能是任何其他)因此可以在编译时计算虚拟基类的子对象 A 的偏移量。

If the compiler knows the type of the object on which you are calling the function, though (as is the case in your example), there should be no overhead because the function call can be dispatched statically (at compile time). In your example, the dynamic type of bar is known to be D (it can't be anything else), so the offset of the virtual base class subobject A can be computed at compile time.

这篇关于当调用非虚拟基本方法时,在C ++中有虚拟继承的惩罚/成本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆