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

最佳答案

vtable本质上是静态的。但是实际上您需要在对象内部有一个vptr成员来执行虚拟调度和其他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++ - 为什么虚拟函数表指针(vfptr)在C++中不能是静态的?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25463790/

10-09 01:07