Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No RTTI but still virtual methods

C++ code can be compiled with run-time type information disabled, which disables dynamic_cast. But, virtual (polymorphic) methods still need to be dispatched based on the run-time type of the target. Doesn't that imply the type information is present anyway, and dynamic_cast should be able to always work?

like image 322
Bart van Heukelom Avatar asked Dec 18 '15 10:12

Bart van Heukelom


People also ask

Why is Rtti needed?

RTTI, Run-Time Type Information, introduces a [mild] form of reflection for C++. It allows to know for example the type of a super class, hence allowing to handle an heterogeneous collection of objects which are all derived from the same base type. in ways that are specific to the individual super-classes.

How do I enable RTTI in C++?

Run-Time Type Discovery (Reflection) Note: The compiler option Project > Options > C++ Compiler > Enable RTTI refers to standard C++ RTTI.

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 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.


1 Answers

Disabling RTTI kills dynamic_cast and typeid but has no impact on virtual functions. Virtual functions are dispatched via the "vtable" of classes which have any virtual functions; if you want to avoid having a vtable you can simply not have virtual functions.

Lots of C++ code in the wild can work without dynamic_cast and almost all of it can work without typeid, but relatively few C++ applications would survive without any virtual functions (or more to the point, functions they expected to be virtual becoming non-virtual).

A virtual table (vtable) is just a per-instance pointer to a per-type lookup table for all virtual functions. You only pay for what you use (Bjarne loves this philosophy, and initially resisted RTTI). With full RTTI on the other hand, you end up with your libraries and executables having quite a lot of elaborate strings and other information baked in to describe the name of each type and perhaps other things like the hierarchical relations between types.

I have seen production systems where disabling RTTI shrunk the size of executables by 50%. Most of this was due to the massive string names that end up in some C++ programs which use templates heavily.

like image 102
John Zwinck Avatar answered Oct 11 '22 00:10

John Zwinck