4

似乎在我读到的所有地方,图书馆都夸耀不需要 RTTI,或者有一篇文章建议不要使用它。它有什么不好,为什么不需要它是一件好事?

谢谢

4

6 回答 6

14
  1. 因为使用它通常意味着您正在颠覆多态性 ( if (type is foo) { do this; } else if (type is bar) { do that; } else ...),这通常意味着您将自己设计到了一个角落,需要重新考虑您的设计。

  2. 因为 C++ 编译器的作者在优化多态行为方面付出了很多努力,但在优化 RTTI 的使用方面却很少。

于 2012-06-27T18:45:01.910 回答
2

C++ 允许使用模板进行大量静态技巧,从而减少了对 RTTI 的需求(一切在编译时都是通用的,但在运行时是具体的)。

相反,处理类的“真正”(SmallTalk-like)OOP 方式需要动态绑定和 RTTI。

C++ 允许两者,但是过多的动态转换和虚函数可能并且确实会降低性能。

于 2012-06-27T18:45:47.627 回答
1

许多精简的嵌入式系统将具有不支持 RTTI 的更简单/更小的实现。如果您的库不需要它,那么您可以移植到更多系统。

于 2012-06-27T18:45:59.307 回答
0

RTTI 为 CRT(C 运行时)引入了更大的角色。C++ 开发人员珍惜执行速度。人们最不想看到的就是引入运行时,这会相对减慢应用程序的速度。

于 2012-06-27T18:52:28.297 回答
-1

RTTI 做了一些在设计时指定的全局唯一序数可以做得更好的事情。不使用 RTTI 的两个原因。

Performance : It is non trivial to come up with a an implementation that scales as well as using ordinals / enums to represent types, and since you don't want namespace collisions you have to use strings, not just strings, globally unique strings. In scripting languages everything is a string inately, thus there is no frowning in these sorts of languages.

Design Elegance : Ordinal based typing works, and if your using it, chances are you had the foresight to design the system properly from the get-go. Such design are pretty much always better than relying on RTTI.

于 2012-06-27T18:52:41.300 回答
-1

It is not a good thing (to not have/use RTTI). Binding should be as late as possible (but not later). Speed and power consumption needs limit you in how late you can bind, but developments in chip technology mean more and more projects can afford to do later binding. Later binding allows design decisions to be made later, when more information is available allowing better decisions.

于 2012-06-29T21:58:53.263 回答