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

标签 c++ virtual-functions dynamic-dispatch

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

最佳答案

vtable 本质上是静态的。但是您需要一个实际位于对象内部的 vptr 成员来执行虚拟分派(dispatch)和其他 RTTI 操作。

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

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

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

可能会像下面这样:

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 };

关于c++ - 为什么在 C++ 中虚拟函数表指针 (vfptr) 不能是静态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25463790/

相关文章:

c++11 - C++中std::shared_ptr的克隆模式

c++ - 有关模板和虚拟功能的问题

c++ - 警告 : overloaded virtual function "Base::process" is only partially overridden in class "derived"

java - Java 中的绑定(bind)和调度有什么区别?

c++ - 为什么我可以获取字符串文字的地址,而不是整数文字的地址?

c++ - openMPI 数据类型可移植性

oop - 我正在尝试创建一个函数,如果元素在 vector 中,则返回 true/false 但我收到错误消息?

C++非连续分配数组

virtual-functions - Swift 有动态调度和虚方法吗?

swift - Swift 中的动态调度和协议(protocol)