是否会发生虚调度

是否会发生虚调度

本文介绍了如果从构造函数/析构函数无条件调用虚函数,是否会发生虚调度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct A
{
    virtual ~A() { f(); }

    virtual void f() {}
};

我已对问题进行了更具体的编辑。.

I've edited my question to be more specific..

在此代码示例中,调用 f()可以使用虚拟调度,还是可以保证等效于 A :: f ()

In this code sample, MAY the call f() use virtual dispatch, or is it guaranteed equivalent to A::f()?

能否提供C ++标准的相关部分?谢谢。

Could you provide relevant section from C++ standard? Thanks.

推荐答案

在构造函数或析构函数内,子类对象尚未构造或已被破坏。 。结果,虚拟调度不会导致使用派生类版本,而是会调用基类版本。

Within a constructor or destructor, the sub-class object has either not yet been constructed, or has already been destroyed. As a result, virtual dispatch does not lead to the derived-class version being used, and instead the base-class version is called.

根据标准, [class.cdtor] / 4

举一个例子:

struct V {
   virtual void f();
   virtual void g();
};
struct A : virtual V {
   virtual void f();
};
struct B : virtual V {
   virtual void g();
   B(V*, A*);
};
struct D : A, B {
   virtual void f();
   virtual void g();
   D() : B((A*)this, this) { }
};
B::B(V* v, A* a) {
    f(); // calls V::f, not A::f
    g(); // calls B::g, not D::g
    v->g(); // v is base of B, the call is well-defined, calls B::g
    a->f(); // undefined behavior, a’s type not a base of B
}

如果调用的函数是纯虚拟的,则从 [class.abstract] / 6

Also note that this can be unsafe if the function that is called is pure virtual, from [class.abstract]/6:

这篇关于如果从构造函数/析构函数无条件调用虚函数,是否会发生虚调度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:51