I had asked a question Do C++ POD types have RTTI? and someone told me in the comments:
POD types do have type_info, but don't have RTTI, and that's possible because type_info isn't always RTTI.
and it seems right as i could get the type_info
of a POD (non-polymorphic) type.
But while I compile this simple program:
#include <iostream>
struct X
{
int a;
};
int main()
{
using namespace std;
std::cout << typeid(X) << std::endl;
return 0;
}
with flag -fno-rtti
of GCC:
$ g++ -fno-rtti main.cpp && ./main
It won't compile:
main.cpp: In function ‘int main()’:
main.cpp:12:26: error: cannot use typeid with -fno-rtti
std::cout << typeid(X) << std::endl;
^
Does that mean type_info
is a part of RTTI, or is it just a behavior of GCC?
The typeid operator requires RunTime Type Identification (RTTI) to be generated, which must be explicitly specified at compile time through a compiler option.
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.
-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 ').
RTTI for basic types such as int and bool is stored in the run-time library. Therefore, object files generated from a C++ program might reference RTTI defined in libc++abi.
RTTI per se is not something really formally defined: C++ only says what typeid
and dynamic_cast
do, not how they're implemented. However, it is convenient indeed to group such kind of operations under a common name which is RTTI.
Notice an implementation is not required to strictly obtain this information at runtime i.e.
if ( typeid(int) == typeid(double) )
could also be determined during the program evaluation, much like std::is_same
. int
is undeniably non-polymorphic (it has no 'dynamic' type). cppreference even claims:
When applied to an expression of polymorphic type, evaluation of a typeid expression may involve runtime overhead (a virtual table lookup), otherwise typeid expression is resolved at compile time.
But it's to be taken cautiously.
Does that mean type_info is a part of RTTI, or is it just a behavior of GCC?
type_info
is a class. You may not construct any object of that type - you only can through typeid
.
-fno-rtti
disable RTTI under GCC: you can't use typeid
, and thereby neither can be type_info
. They're very close each other.
To conclude, the original quote is totally right:
POD types do have
type_info
, but don't have RTTI, and that's possible because type_info isn't always RTTI.
The runtime information is available through typeid
. There is just nothing dynamic to consider (indeed, dynamic_cast
would make no sense).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With