C++ 中的RTTI机制详解

前言node

RTTI是”Runtime Type Information”的缩写,意思是运行时类型信息,它提供了运行时肯定对象类型的方法。RTTI并非什么新的东西,很早就有了这个技术,可是,在实际应用中使用的比较少而已。而我这里就是对RTTI进行总结,今天我没有用到,并不表明这个东西没用。学无止境,先从typeid函数开始讲起。ios

typeid函数编程

typeid的主要做用就是让用户知道当前的变量是什么类型的,对于内置数据类型以及自定义数据类型都生效,好比如下代码:安全

#include <iostream>
#include <typeinfo>
using namespace std;
 
int main()
{
     short s = 2;
     unsigned ui = 10;
     int i = 10;
     char ch = 'a';
     wchar_t wch = L'b';
     float f = 1.0f;
     double d = 2;
 
     cout<<typeid(s).name()<<endl; // short
     cout<<typeid(ui).name()<<endl; // unsigned int
     cout<<typeid(i).name()<<endl; // int
     cout<<typeid(ch).name()<<endl; // char
     cout<<typeid(wch).name()<<endl; // wchar_t
     cout<<typeid(f).name()<<endl; // float
     cout<<typeid(d).name()<<endl; // double
 
     return 0;
}

对于C++支持的内建类型,typeid能彻底支持,咱们经过调用typeid函数,咱们就能知道变量的信息。对于咱们自定义的结构体,类呢?函数

#include <iostream>
#include <typeinfo>
using namespace std;
 
class A
{
public:
     void Print() { cout<<"This is class A."<<endl; }
};
 
class B : public A
{
public:
     void Print() { cout<<"This is class B."<<endl; }
};
 
struct C
{
     void Print() { cout<<"This is struct C."<<endl; }
};
 
int main()
{
     A *pA1 = new A();
     A a2;
 
     cout<<typeid(pA1).name()<<endl; // class A *
     cout<<typeid(a2).name()<<endl; // class A
 
     B *pB1 = new B();
     cout<<typeid(pB1).name()<<endl; // class B *
 
     C *pC1 = new C();
     C c2;
 
     cout<<typeid(pC1).name()<<endl; // struct C *
     cout<<typeid(c2).name()<<endl; // struct C
 
     return 0;
}

是的,对于咱们自定义的结构体和类,tpyeid都能支持。在上面的代码中,在调用完typeid以后,都会接着调用name()函数,能够看出typeid函数返回的是一个结构体或者类,而后,再调用这个返回的结构体或类的name成员函数;其实,typeid是一个返回类型为type_info类型的函数。那么,咱们就有必要对这个type_info类进行总结一下,毕竟它实际上存放着类型信息。ui

type_info类url

去掉那些该死的宏,在Visual Studio 2012中查看type_info类的定义以下:spa

class type_info
{
public:
    virtual ~type_info();
    bool operator==(const type_info& _Rhs) const; // 用于比较两个对象的类型是否相等
    bool operator!=(const type_info& _Rhs) const; // 用于比较两个对象的类型是否不相等
    bool before(const type_info& _Rhs) const;
 
    // 返回对象的类型名字,这个函数用的不少
    const char* name(__type_info_node* __ptype_info_node = &__type_info_root_node) const;
    const char* raw_name() const;
private:
    void *_M_data;
    char _M_d_name[1];
    type_info(const type_info& _Rhs);
    type_info& operator=(const type_info& _Rhs);
    static const char * _Name_base(const type_info *,__type_info_node* __ptype_info_node);
    static void _Type_info_dtor(type_info *);
};

  

在type_info类中,复制构造函数和赋值运算符都是私有的,同时也没有默认的构造函数;因此,咱们没有办法建立type_info类的变量,例如type_info A;这样是错误的。那么typeid函数是如何返回一个type_info类的对象的引用的呢?我在这里不进行讨论,思路就是类的友元函数。.net

typeid函数的使用指针

typeid使用起来是很是简单的,经常使用的方式有如下两种:

1.使用type_info类中的name()函数返回对象的类型名称

就像上面的代码中使用的那样;可是,这里有一点须要注意,好比有如下代码:

#include <iostream>
#include <typeinfo>
using namespace std;
 
class A
{
public:
     void Print() { cout<<"This is class A."<<endl; }
};
 
class B : public A
{
public:
     void Print() { cout<<"This is class B."<<endl; }
};
 
int main()
{
     A *pA = new B();
     cout<<typeid(pA).name()<<endl; // class A *
     cout<<typeid(*pA).name()<<endl; // class A
     return 0;
}

使用了两次typeid,可是两次的参数是不同的;输出结果也是不同的;当我指定为pA时,因为pA是一个A类型的指针,因此输出就为class A *;当我指定*pA时,它表示的是pA所指向的对象的类型,因此输出的是class A;因此须要区分typeid(*pA)和typeid(pA)的区别,它们两个不是同一个东西;可是,这里又有问题了,明明pA实际指向的是B,为何获得的倒是class A呢?咱们在看下一段代码:

#include <iostream>
#include <typeinfo>
using namespace std;
 
class A
{
public:
     virtual void Print() { cout<<"This is class A."<<endl; }
};
 
class B : public A
{
public:
     void Print() { cout<<"This is class B."<<endl; }
};
 
int main()
{
     A *pA = new B();
     cout<<typeid(pA).name()<<endl; // class A *
     cout<<typeid(*pA).name()<<endl; // class B
     return 0;
}

好了,我将Print函数变成了虚函数,输出结果就不同了,这说明什么?这就是RTTI在捣鬼了,当类中不存在虚函数时,typeid是编译时期的事情,也就是静态类型,就如上面的cout<<typeid(*pA).name()<<endl;输出class A同样;当类中存在虚函数时,typeid是运行时期的事情,也就是动态类型,就如上面的cout<<typeid(*pA).name()<<endl;输出class B同样,关于这一点,咱们在实际编程中,常常会出错,必定要谨记。

2.使用type_info类中重载的==和!=比较两个对象的类型是否相等

这个会常常用到,一般用于比较两个带有虚函数的类的对象是否相等,例如如下代码: 

#include <iostream>
#include <typeinfo>
using namespace std;
 
class A
{
public:
     virtual void Print() { cout<<"This is class A."<<endl; }
};
 
class B : public A
{
public:
     void Print() { cout<<"This is class B."<<endl; }
};
 
class C : public A
{
public:
     void Print() { cout<<"This is class C."<<endl; }
};
 
void Handle(A *a)
{
     if (typeid(*a) == typeid(A))
     {
          cout<<"I am a A truly."<<endl;
     }
     else if (typeid(*a) == typeid(B))
     {
          cout<<"I am a B truly."<<endl;
     }
     else if (typeid(*a) == typeid(C))
     {
          cout<<"I am a C truly."<<endl;
     }
     else
     {
          cout<<"I am alone."<<endl;
     }
}
 
int main()
{
     A *pA = new B();
     Handle(pA);
     delete pA;
     pA = new C();
     Handle(pA);
     return 0;
}
这里输出的结果为:
I am a B truly.
I am a C truly.

这是一种用法,呆会我再总结如何使用dynamic_cast来实现一样的功能。

 

dynamic_cast的内幕

在这篇《static_cast、dynamic_cast、const_cast和reinterpret_cast总结》的文章中,也介绍了dynamic_cast的使用,对于dynamic_cast究竟是如何实现的,并无进行说明,而这里就要对于dynamic_cast的内幕一探究竟。首先来看一段代码:

#include <iostream>
#include <typeinfo>
using namespace std;
 
class A
{
public:
     virtual void Print() { cout<<"This is class A."<<endl; }
};
 
class B
{
public:
     virtual void Print() { cout<<"This is class B."<<endl; }
};
 
class C : public A, public B
{
public:
     void Print() { cout<<"This is class C."<<endl; }
};
 
int main()
{
     A *pA = new C;
     //C *pC = pA; // Wrong
     C *pC = dynamic_cast<C *>(pA);
     if (pC != NULL)
     {
          pC->Print();
     }
     delete pA;
}

这里输出为:This is class C

在上面代码中,若是咱们直接将pA赋值给pC,这样编译器就会提示错误,而当咱们加上了dynamic_cast以后,一切就ok了。那么dynamic_cast在后面干了什么呢?

dynamic_cast主要用于在多态的时候,它容许在运行时刻进行类型转换,从而使程序可以在一个类层次结构中安全地转换类型,把基类指针(引用)转换为派生类指针(引用)。我在《COM编程——接口的背后》这篇博文中总结的那样,当类中存在虚函数时,编译器就会在类的成员变量中添加一个指向虚函数表的vptr指针,每个class所关联的type_info object也经由virtual table被指出来,一般这个type_info object放在表格的第一个slot。当咱们进行dynamic_cast时,编译器会帮咱们进行语法检查。若是指针的静态类型和目标类型相同,那么就什么事情都不作;不然,首先对指针进行调整,使得它指向vftable,并将其和调整以后的指针、调整的偏移量、静态类型以及目标类型传递给内部函数。其中最后一个参数指明转换的是指针仍是引用。二者惟一的区别是,若是转换失败,前者返回NULL,后者抛出bad_cast异常。对于在typeid函数的使用中所示例的程序,我使用dynamic_cast进行更改,代码以下:

#include <iostream>
#include <typeinfo>
using namespace std;
 
class A
{
public:
     virtual void Print() { cout<<"This is class A."<<endl; }
};
 
class B : public A
{
public:
     void Print() { cout<<"This is class B."<<endl; }
};
 
class C : public A
{
public:
     void Print() { cout<<"This is class C."<<endl; }
};
 
void Handle(A *a)
{
     if (dynamic_cast<B*>(a))
     {
          cout<<"I am a B truly."<<endl;
     }
     else if (dynamic_cast<C*>(a))
     {
          cout<<"I am a C truly."<<endl;
     }
     else
     {
          cout<<"I am alone."<<endl;
     }
}
 
int main()
{
     A *pA = new B();
     Handle(pA);
     delete pA;
     pA = new C();
     Handle(pA);
     return 0;
}

 

这里输出的结果为:
I am a B truly.
I am a C truly.这个是使用dynamic_cast进行改写的版本。实际项目中,这种方法会使用的更多点。
相关文章
相关标签/搜索