How is dynamic_cast implemented

前端 未结 3 681
温柔的废话
温柔的废话 2020-12-08 09:40

Consider this simple hierarchy:

class Base { public: virtual ~Base() { } };
class Derived : public Base { };

Trying to downcast Base*

3条回答
  •  生来不讨喜
    2020-12-08 10:08

    How can the dynamic_cast know whether Derived2 was derived from Derived (what if Derived was declared in a different library)?

    The answer to that is surprisingly simple: dynamic_cast can know this by keeping this knowledge around.

    When the compiler generates code it keeps around the data about the class hierarchies in some sort of table that dynamic_cast can look up later. That table can be attached to the vtable pointer for easy lookup by the dynamic_cast implementation. The data neeeded for typeid for those classes can also be stored along with those.

    If libraries are involved, this sort of thing usually requires these type information structures to be exposed in the libraries, just like with functions. It is possible, for example, to get a linker error that looks like "Undefined reference to 'vtable for XXX'" (and boy, are those annoying!), again, just like with functions.

提交回复
热议问题