为什么在C ++中虚函数表指针(vfptr)不能是静态的? [英] Why can't the virtual function table pointer (vfptr) be static in C++?

查看:481
本文介绍了为什么在C ++中虚函数表指针(vfptr)不能是静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If the virtual function table is the same for all objects of the class, then why can't the pointer to that table (vfptr) be static and be shared across all the objects?

推荐答案

vtable本质上是静态的。但是你需要一个实际在对象内的vptr成员来做虚拟分派和其他RTTI操作。

The vtable is essentially static. But you need a vptr member actually inside the object to do virtual dispatch and other RTTI operations.

在vptr实现上,这个C ++代码:

On a vptr implementation, this C++ code:

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)不能是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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