虚拟表/调度表 [英] Virtual table/dispatch table

查看:109
本文介绍了虚拟表/调度表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我所知道的CPP,每个类都有自己的vtable。

From what I know of CPP, each class has its own vtable.

但是,维基百科链接提及:

However this wikipedia link mentions:


对象的分派表将
包含对象的
动态绑定方法的地址。方法
调用通过从对象的
调度表中获取
方法的地址来执行。调度表是
,对于属于同一个类的
的所有对象是相同的,因此它们之间通常是共享的

An object's dispatch table will contain the addresses of the object's dynamically bound methods. Method calls are performed by fetching the method's address from the object's dispatch table. The dispatch table is the same for all objects belonging to the same class, and is therefore typically shared between them.

有人可以请一些光。

感谢!

推荐答案

class PureVirtual {
   public:
       virtual void methodA() = 0;
       virtual void methodB() = 0;
};

class Base : public PureVirtual {
   public:
        virtual void methodA();
        void methodC();
   private:
        int x;
 };

 class Derived : public Base {
    public:
         virtual void methodB();
    private:
         int y;
 };

因此,给定一个Derived类型的对象可能看起来像:

So, given an object of type Derived it might look like:

                         ------------
 Known offset for vtable |  0xblah  | -------> [Vtable for type "Derived"]
                         ------------
 Known offset for x      |  3       |
                         ------------
 Known offset for y      |  2       |
                         ------------

派生看起来像:

                            ------------
 Known offset for "methodA" | 0xblah1   | ------> methodA from Base
                            -------------
 Known offset for "methodB" | 0xblah2   | ------> methodB from Derived
                            -------------

注因为methodC不是虚拟的,它根本不在vtable中。还要注意,类Derived的所有实例都有一个指向同一个共享vtable对象的vtable指针(因为它们具有相同的类型)。

Note that since "methodC" was not virtual, it is not in the vtable at all. Also note that all instances of class Derived will have a vtable pointer to the same, shared vtable object (since they have the same type).

虽然C ++和Java略有不同,思路不是不兼容。从概念的角度来看,关键的区别是,Java方法是虚拟的,除非声明为final。在C ++中,必须明确地为函数在vtable中提供关键字virtual。任何不在vtable中的都将使用编译时类型而不是对象的运行时类型来分派。

Though the implementations for C++ and Java are slightly different, the ideas are not incompatible. The key difference, from a conceptual standpoint, is that Java methods are "virtual" unless declared "final". In C++ the keyword "virtual" must be given explicitly for the function to be in the vtable. Anything not in vtable will be dispatched using the compile-time types rather than the runtime type of the object.

这篇关于虚拟表/调度表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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