显式类型标识符与 RTTI
与 RTTI 相比,使用自己的类型标识符有什么优势吗?
例如
class A { virtual int mytype() = 0; };
class B : public A { int mytype() {return 1;} };
class C : public A { int mytype() {return 2;} };
可以更快吗?更少的开销?或者在这种情况下应该始终使用 RTTI 吗?
is there any advantage of using your own type identifier over RTTI?
e.g.
class A { virtual int mytype() = 0; };
class B : public A { int mytype() {return 1;} };
class C : public A { int mytype() {return 2;} };
Could it be faster? Less overhead? Or should one always use RTTI in such a situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在测试之前,不要假设 RTTI 的开销会比您的解决方案更多/更少。
您应该尝试这两种解决方案并测量性能以获得可靠的答案。
实际上,几年前我问了自己同样的问题,最后我添加了一个成员变量来“紧固”类型测试,就像您所做的那样。结果我的代码不必要地混乱了愚蠢的测试,而一些
dynamic_cast<>
可以完成相同的工作(事实上,更好的工作)。从那时起,我重构了代码以使用
dynamic_cast<>
,并且我不会再回去了。作为脚注:如果您的类是多态的,那么您已经为此“付费”了,因此只需使用
dynamic_cast<>
即可。Don't assume that RTTI will have more/less overhead than your solution before testing it.
You should try both solutions and measure the performances to get a reliable answer.
I actually asked myself the same question a few years ago and I ended up adding a member variable to "fasten" the type testing, just like you did. Turned out my code was needlessly cluttered with stupid tests while some
dynamic_cast<>
would have done the same job (in fact, a better job).I refactored the code to use
dynamic_cast<>
since then and I wouldn't go back.As a foot-note: if your classes are polymorphic, you already "paid" for this anyway, so just go with
dynamic_cast<>
.使用自定义类型标识符的缺点(对于多态类型)是:
类继承。你需要分配
唯一的整数或枚举值
给定层次结构中的所有类
继承就像
A->B->D
。对于诸如
A *p = new D;
的情况,自定义类型标识将不允许将B*
与p
匹配(即使它是有效的) )。您需要了解这些情况。
另一方面,
多态类型(所以
继承链不包含
虚拟功能无法利用RTTI)
RTTI 导致差异减小,如果确实如此
对你来说很重要
但是,正如你在评论中提到的,对于较小的继承链,跟踪你自己的类型没有什么坏处。例如
The disadvantages (for polymorphic types) with custom type identifier are:
class inherited. You need to assign
a unique integer or enum value for
all the classes in a given hierarchy
inheritance is like,
A->B->D
.For situations like,
A *p = new D;
the custom type identification will not allow to matchB*
withp
(even though it's valid).You need to be aware of these situations.
On the other had,
polymorphic types (so the
inheritance chain not containing
virtual functions cannot leverage RTTI)
difference decrease due to RTTI, if it really
matters to you
But, as you mentioned in your comment, for smaller inheritance chain, there is no harm in keeping track of your own typing. e.g.
http://en.wikibooks.org/wiki/C%2B%2B_Programming/RTTI
因此,如果您需要它在没有虚函数的类上工作,您必须自己实现它。
http://en.wikibooks.org/wiki/C%2B%2B_Programming/RTTI
So, if you need it to work on classes without virtual functions, you'd have to implement it yourself.