简体   繁体   English

运行时类型信息的奇怪行为

[英]Strange behavior of run-time type information

I've two class Base and Derived as this: 我有两个Base类和Derived类:

class Base
{
public:
};

class Derived : public Base
{
public:
};

and main function: 和主要功能:

int main()
{
    Base* ptr = new Derived;

    std::cout << typeid(*ptr).name() << endl;

    delete ptr;

    system("pause");
}

Program outputs shows class Base where I expected it will show class Derived . 程序输出显示class Base ,我期望它将显示class Derived But when I've added a virtual method in the Base class, now outputs shows class Derived ! 但是,当我在Base类中添加了虚方法时,现在输出显示class Derived

Why RTTI needs at least one virtual method? 为什么RTTI需要至少一种虚拟方法?

Because the language specification says so. 因为语言规范是这样说的。 RTTI only works on polymorphic types; RTTI仅适用于多态类型。 that is, types with virtual functions. 即具有虚函数的类型。 For other types, typeid returns the type info for the static type of its argument. 对于其他类型, typeid返回其参数的静态类型的类型信息。

If you're asking for a rationale for this: it has a run-time cost (typically, a pointer in each object to the per-class metadata, which supports both virtual dispatch and RTTI), and it would be a shame if you had to pay that price for all types, whether or not you want to use RTTI on them. 如果您要求这样做的理由:它具有运行时成本(通常,每个对象中的指向每个类元数据的指针,该指针同时支持虚拟调度和RTTI),如果您这样做,那将是很可惜的无论您是否要对它们使用RTTI,都必须为所有类型支付该价格。

Too long for a comment. 评论太久了。

1) Refers to a std::type_info object representing the type type. 1)引用代表类型类型的std :: type_info对象。 If type is a reference type, the result refers to the referenced type. 如果type是引用类型,则结果引用引用的类型。

2) Examines the expression expression 2)检查表情表达

a) If expression is a glvalue expression that identifies an object of a polymorphic type (that is, a class that declares or inherits at least one virtual function), the typeid expression evaluates the expression and then refers to the std::type_info object that represents the dynamic type of the expression . a) 如果expression是一个glvalue表达式,它标识多态类型的对象 (即,一个声明或继承了至少一个虚函数的类), 则typeid表达式将评估该表达式,然后引用该std :: type_info对象,表示表达式的动态类型 If the result of the evaluated expression is a null pointer, an exception of type std::bad_typeid or a type derived from std::bad_typeid is thrown. 如果求值表达式的结果为空指针,则抛出std :: bad_typeid类型或从std :: bad_typeid派生的类型的异常。

b) If expression is not a glvalue expression of polymorphic type, typeid does not evaluate the expression, and the std::type_info object it identifies represents the static type of the expression . b) 如果expression不是多态类型的glvalue表达式,则typeid不评估该表达式,并且它标识的std :: type_info对象表示该表达式的静态类型 Lvalue-to-rvalue, array-to-pointer, or function-to-pointer conversions are not performed. 不执行左值到右值,数组到指针或函数到指针的转换。

Thus the behavior is expected, since in one case the class is polymorphic, and in the other it's not. 因此,这种行为是可以预期的,因为在一种情况下该类是多态的,而在另一种情况下则不是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM