type_info不是RTTI的一部分吗? [英] Is type_info not a part of RTTI?
问题描述
我曾问过一个问题 Do C ++ POD类型是否具有RTTI?,有人告诉我在评论:
I had asked a question Do C++ POD types have RTTI? and someone told me in the comments:
POD类型有type_info,但没有RTTI,这可能
,因为type_info不总是RTTI。
POD types do have type_info, but don't have RTTI, and that's possible because type_info isn't always RTTI.
似乎是正确的,因为我可以得到 type_info $ c
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;
}
标志 -fno-rtti
of GCC:
$ g++ -fno-rtti main.cpp && ./main
它不会编译:
main.cpp: In function ‘int main()’:
main.cpp:12:26: error: cannot use typeid with -fno-rtti
std::cout << typeid(X) << std::endl;
^
这意味着 type_info
推荐答案
是 / h2>
RTTI本身并不是真正的定义:C ++只说了 typeid
和 dynamic_cast
do,而不是如何实现。
Abstract
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))
也可以在程序评估期间确定,很像 std :: is_same
。 int
是不可否认的非多态性(它没有'动态'类型)。 cppreference 甚至声称:
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:
当应用于多态类型的表达式时,对typeid表达式的求值可能涉及运行时开销(虚拟表查找),否则typeid表达式在编译时解析。
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.
但是要小心。
平均值type_info是RTTI的一部分,还是仅仅是GCC的行为?
Does that mean type_info is a part of RTTI, or is it just a behavior of GCC?
type_info
是一个类。你不能构造任何类型的对象 - 你只能通过 typeid
。
type_info
is a class. You may not construct any object of that type - you only can through typeid
.
-fno-rtti
禁用GCC下的RTTI:您不能使用 typeid
因此既不能 type_info
。
总而言之,原始报价完全正确:
To conclude, the original quote is totally right:
POD类型有
type_info
,但没有RTTI,这是可能的,因为type_info不总是RTTI。
POD types do have
type_info
, but don't have RTTI, and that's possible because type_info isn't always RTTI.
运行时信息可通过 typeid
获取。没有什么动态可以考虑(事实上, dynamic_cast
是没有意义的)。
The runtime information is available through typeid
. There is just nothing dynamic to consider (indeed, dynamic_cast
would make no sense).
这篇关于type_info不是RTTI的一部分吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!