为什么虚函数表指针(vfptr)在C++中不能是静态的?

sn7*_*710 5 c++ virtual-functions dynamic-dispatch

如果虚拟函数表对于类的所有对象都是相同的,那么为什么指向该表的指针(vfptr)不能是静态的并且在所有对象之间共享?

asc*_*ler 4

vtable本质上是静态的。但是您实际上需要对象内部的 vptr 成员来执行虚拟调度和其他 RTTI 操作。

在 vptr 实现上,此 C++ 代码:

class Base {
public:
    virtual void f();
};

class Derived : public Base {
public:
    virtual void f();
};
Run Code Online (Sandbox Code Playgroud)

其行为可能类似于这样:

class Base {
public:
    Base::Base() : m_vptr(&Base_vtab) {}
    Base::Base(const Base& b) : m_vptr(&Base_vtab) {}
    void f() { (m_vptr->f_impl)(this); }
protected:
    struct VTable {
        void (*f_impl)(Base* self);
    };
    const VTable* m_vptr;
    static const VTable Base_vtab;
private:
    static void Base_f(Base* self);
};

const Base::VTable Base::Base_vtab = { &Base::Base_f };

class Derived : public Base {
public:
    Derived::Derived() : Base() { m_vtpr = &Derived_vtab; }
    Derived::Derived(const Derived& d) : Base(d) { m_vptr = &Derived_vtab; }
    Derived::~Derived() { m_vptr = &Base::Base_vtab; }
protected:
    static const VTable Derived_vtab;
private:
    static void Derived_f(Derived* self);
    static void Derived_f(Base* self) { Derived_f(static_cast<Derived*>(self)); }
};

const Base::VTable Derived::Derived_vtab = { &Derived::Derived_f };
Run Code Online (Sandbox Code Playgroud)