gpt4 book ai didi

c++ - 使用typeid实现RTTI

转载 作者:搜寻专家 更新时间:2023-10-30 23:59:30 24 4
gpt4 key购买 nike

我是高级 C++ 主题研究的新手,所以如果问题听起来太明显,请原谅我。

我一直在阅读有关在 C++ 中我们可以在运行时获取对象类型信息的各种方法,通常称为 RTTI。

但是,我对它是如何工作的感到困惑。我看过一些在解释RTTI时经常提到的东西。其中之一是使用 dynamic_cast<> 将对象动态转换为其他对象。另一种是在运行时使用 typeid 来确定对象的类型。

我想知道使用 typeid 是否是在 C++ 中实现 RTTI 的正确方法,如果是,那么 typeid 运算符实际上如何能够在运行时确定对象的类型(它是否分析内存中的对象 blob?)

如果使用 typeid 不是正确的方法,那么请建议一些其他的实现方法。

最佳答案

重要:
理想情况下,如果您需要识别对象的类型,您需要重新审视您的设计,因为很可能您在那里遗漏了一些东西并且您违反了 SOLID OOP 规则。

C++ 标准提供dynamic_casttypeid 作为确定对象类型 的两种方法。两者都有其优点和局限性。它们如何识别类型 是一个依赖于实现的细节,但通常它们通过在对象的 vtable 中维护指向类型信息结构的指针来实现。如果您完全不知道 vtable 是什么,Marshal Clines C++ Faq 提供了很好的解释 here .

您可以在
中找到大多数编译器使用的实现细节<强> Technical Report on C++ Performance

相关摘录:

5.3.7 Type Information

Given an object of a polymorphic class (a class with at least one virtual function), atype_info object can be obtained through the use of the typeid operator. Inprinciple, this is a simple operation which involves finding the virtual function table,through that finding the most-derived class object of which the object is part, and then extracting a pointer to the type_info object from that object’s virtual function table (orequivalent).


5.3.8 Dynamic Cast

Given a pointer to an object of a polymorphic class, a cast to a pointer to another basesubobject of the same derived class object can be done using a dynamic_cast. Inprinciple, this operation involves finding the virtual function table, through that findingthe most-derived class object of which the object is part, and then using type informationassociated with that object to determine if the conversion (cast) is allowed, and finallyperforming any required adjustments of the this pointer. In principle, this checkinginvolves the traversal of a data structure describing the base classes of the most derivedclass. Thus, the run-time cost of a dynamic_cast may depend on the relative positionsin the class hierarchy of the two classes involved.

关于c++ - 使用typeid实现RTTI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16266339/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com