Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic_cast with RTTI disabled

I'm curious to know what happens when compiling code with a dynamic cast whith RTTI disabled (either with -fno-rttion 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 ?

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() ; 
like image 356
Louen Avatar asked Oct 07 '11 12:10

Louen


People also ask

Does dynamic_cast required RTTI?

The fact, that the cast is safe is known by the compiler at compile time. This means, that dynamic_cast does not need to use RTTI.

Can dynamic cast be used with references?

The dynamic_cast operator can be used to cast to reference types. C++ reference casts are similar to pointer casts: they can be used to cast from references to base class objects to references to derived class objects.

What is FNO RTTI?

-fno-rtti. Disable generation of information about every class with virtual functions for use by the C++ runtime type identification features (` dynamic_cast ' and ` typeid '). If you don't use those parts of the language, you can save some space by using this flag.

What is RTTI in C++?

Run-time type information (RTTI) is a mechanism that allows the type of an object to be determined during program execution. RTTI was added to the C++ language because many vendors of class libraries were implementing this functionality themselves.


2 Answers

Reading the standard, in 5.2.7/6 we find that unless the target is an unambiguous base of the source, source must be a polymorphic type. Then in 10.3/1

Virtual functions support dynamic binding and objectoriented programming. A class that declares or inherits a virtual function is called a polymorphic class.

In other words the standard doesn't seem to say anything about your question. In this case, the standard doesn't allow for a compiler to turn off RTTI so for each compiler you need to check its documentation to see what would happen. Based on this reading, I think this is a compiler question, not a C++ language question as the tag indicates.

Alternately you can avoid the problem completely by just using static_cast when you know it's sufficient.

like image 188
Mark B Avatar answered Sep 22 '22 19:09

Mark B


In MSVC, if your code is not compiled with RTTI enabled, a __non_rtti_object exception will be thrown, if the cast cannot be performed without a run-time check.

like image 42
John Dibling Avatar answered Sep 21 '22 19:09

John Dibling