问题描述
我好奇地知道当使用动态转换编译代码时,RTTI禁用
(在GCC上使用 -fno-rtti
或使用 / GR -
在visual studio)。编译器是否回退到 static_cast
?因为(至少在VS)它只发出警告,编译代码会做什么?
I'm curious to know what happens when compiling code with a dynamic cast whith RTTI disabled(either with -fno-rtti
on GCC or with /GR-
on visual studio). Does the compiler "falls back" to static_cast
? Since (at least on VS) it does only issue a warning, what will the compiled code do ?
更具体地说,如果我编译没有RTTI代码,我确信没有可能的错误dynamic_cast(即其中 dynamic_cast
可以安全地替换为 static_cast
)like this one:
More specifically, what bad things could happen if I compile without RTTI a code where I'm sure that there are no error possible with dynamic_cast (i.e. where dynamic_cast
could be safely replaced by a static_cast
) like this one :
class A{ /*...*/ } ;
class B : public A {
int foo() { return 42 ;}
} ;
//...
A * myA = new B() ;
int bar = (dynamic_cast<B*>(myA))->foo() ;
推荐答案
最简单的方法是尝试。
The easiest way to find out is to try it.
您会发现,一些的动态强制转换会被标记为非法。有些不会。例如,当您使用动态转换以向上转换到无歧义的基类时,转换在编译时就已知。
What you will find is that some of your dynamic casts will be flagged as illegal. Some won't. For example, the conversion is known at compile time when you use dynamic cast to upcast to an unambiguous base class.
附录
Re由于(至少在VS)它只发出警告 ...
忽略警告在你的危险。最好的做法是确保你的代码编译没有警告,警告级别设置非常高(可能转换为错误)。第二最好是看看你得到的每一个警告,并确保没有不幸的事情发生。在这种情况下,会发生不愉快的事情。你真的不应该关心这个不愉快的事件是如何实现的。你应该关心的是摆脱它。
Addendum
Re "Since (at least on VS) it does only issue a warning ..."Ignore warnings at your peril. The best thing to do is to ensure that your code compiles without warnings, with warning levels set very high (and possibly converted to errors). Second best is to look at each and every warning you get and ensure that nothing untoward happens. In this case, something untoward will happen. You really should not care how that untoward event is implemented. What you should care about is getting rid of it.
这篇关于dynamic_cast,禁用RTTI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!