C++ 中的RTTI机制详解
前言
RTTI是”Runtime Type Information”的缩写,意思是运行时类型信息,它提供了运行时确定对象类型的方法。RTTI并不是什么新的东西,很早就有了这个技术,但是,在实际应用中使用的比较少而已。而我这里就是对RTTI进行总结,今天我没有用到,并不代表这个东西没用。学无止境,先从typeid函数开始讲起。
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类进行总结一下,毕竟它实际上存放着类型信息。
type_info类
去掉那些该死的宏,在Visual Studio 2012中查看type_info类的定义如下:
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类的对象的引用的呢?我在这里不进行讨论,思路就是类的友元函数。
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进行改写的版本。实际项目中,这种方法会使用的更多点。
C++ 中的RTTI机制详解的更多相关文章
- JAVA中的GC机制详解
优秀Java程序员必须了解的GC工作原理 一个优秀的Java程序员必须了解GC的工作原理.如何优化GC的性能.如何与GC进行有限的交互,因为有一些应用程序对性能要求较高,例如嵌入式系统.实时系统等,只 ...
- Tomcat与Spring中的事件机制详解
最近在看tomcat源码,源码中出现了大量事件消息,可以说整个tomcat的启动流程都可以通过事件派发机制串起来,研究透了tomcat的各种事件消息,基本上对tomcat的启动流程也就有了一个整体的认 ...
- 关于MySQL中的锁机制详解
锁概述 MySQL的锁机制,就是数据库为了保证数据的一致性而设计的面对并发场景的一种规则. 最显著的特点是不同的存储引擎支持不同的锁机制,InnoDB支持行锁和表锁,MyISAM支持表锁. 表锁就是把 ...
- JAVA中的反射机制 详解
主要介绍以下几方面内容 理解 Class 类 理解 Java 的类加载机制 学会使用 ClassLoader 进行类加载 理解反射的机制 掌握 Constructor.Method.Field 类的用 ...
- C++ 中的类型转换机制详解
Tips: This article based on Scott Meyers's <<Effective C++>> article 27: Minimize Castin ...
- react第五单元(事件系统-原生事件-react中的合成事件-详解事件的冒泡和捕获机制)
第五单元(事件系统-原生事件-react中的合成事件-详解事件的冒泡和捕获机制) 课程目标 深入理解和掌握事件的冒泡及捕获机制 理解react中的合成事件的本质 在react组件中合理的使用原生事件 ...
- 从mixin到new和prototype:Javascript原型机制详解
从mixin到new和prototype:Javascript原型机制详解 这是一篇markdown格式的文章,更好的阅读体验请访问我的github,移动端请访问我的博客 继承是为了实现方法的复用 ...
- 浏览器 HTTP 协议缓存机制详解
最近在准备优化日志请求时遇到了一些令人疑惑的问题,比如为什么响应头里出现了两个 cache control.为什么明明设置了 no cache 却还是发请求,为什么多次访问时有时请求里带了 etag, ...
- JVM的垃圾回收机制详解和调优
JVM的垃圾回收机制详解和调优 gc即垃圾收集机制是指jvm用于释放那些不再使用的对象所占用的内存.java语言并不要求jvm有gc,也没有规定gc如何工作.不过常用的jvm都有gc,而且大多数gc都 ...
随机推荐
- const 关键字总结
int a; const int* p = &a; == int const * p = &a; 表示通过p不能修改a的值. const int a; int *p = &a ...
- Linux 循环创建多个线程
这里说一下相关的基础知识: 线程概念 什么是线程 LWP:light weight process 轻量级的进程,本质仍是进程(在Linux环境下) 进程:独立地址空间,拥有PCB 线 ...
- 【转】解决Eclipse中SVN版本信息不显示的问题
eclipse 中使用 svn 插件,原本正常,未作任何更改,最近几天突然eclipse 中查看文件时,文件后面的 版本号 . 文件的状态图标 等等都不见了.以为有插件冲突,卸载了好多其他的相关的插件 ...
- servlet中的执行顺序
- Qt的action控件中采用默认绑定,没有connect显示绑定!!!
使用qt创建界面时,可以选用代码设计也可以选用qt design来设计.最近看我同事的代码,以前写action都是使用connect链接槽函数的, 网上大多数人都是这样,然后我就纳闷,怎么没有conn ...
- Ubuntu下面的docker开启ssh服务
选择主流的openssh-server作为服务端: root@161f67ccad50:/# apt-get install openssh-server -y Reading package lis ...
- 用jQuery实现轮播图效果,js中的排他思想
---恢复内容开始--- jQuery实现轮播图不用单独加载. 思路: a. 通过$("#id名");选择需要的一类标签,获得一个伪数组 b.由于是伪数组的原因,而对数组的处理最多 ...
- metasploit framework(六):信息收集
nmap 扫描 扫描完毕之后,hosts查看扫描的结果 auxiliary 扫描 使用arpsweep模块扫描 查看设置 设置网卡和目标IP 设置伪造的源IP和源MAC set SHOST <伪 ...
- 安装好kali要做的事
更换更新源 vim /etc/apt/sources.list #中科大deb http://mirrors.ustc.edu.cn/kali kali-rolling main non-free c ...
- Android学习路-Android Studio的工程目录
说明:下图为一个app的工程目录,如果在res下随便建立文件夹(比如test等名字)是不会显示在工程内的