Why do I need to #include <typeinfo> when using the typeid operator?

北慕城南 提交于 2019-12-18 07:35:12

问题


The typeid represents a C++ RTTI operator being also a C++ keyword. It returns a std::type_info object that holds (dynamic) type specific information.

From what I understood from various sources, one MUST include <typeinfo> when using typeid, otherwise the program is ill-formed. In fact, my gcc5.2 compiler doesn't even compile the program if I don't include the before-mentioned header. I don't understand why is a header inclusion mandated for the usage of a C++ keyword. I understand mandating a header for whenever we use some object declared/defined in that header, but typeid is not of a class type. So what is the reason behind this enforcement of including the header <typeinfo>?


回答1:


The next paragraph:

The typeid expression is lvalue expression which refers to an object with static storage duration, of the polymorphic type const std::type_info or of some type derived from it.

Because it is an lvalue expression, which uses reference initialization to declare an initializer of std::type_info. <typeinfo> contains the definition for that object.




回答2:


typeid is not the only one that needs header

new also requires header <new> in some cases

Note: the implicit declarations do not introduce the names std, std::bad_alloc, and std::size_t, or any other names that the library uses to declare these names. Thus, a new-expression, delete-expression or function call that refers to one of these functions without including the header is well-formed. However, referring to std, std::bad_alloc, and std::size_t is ill-formed unless the name has been declared by including the appropriate header. —end note

See abhay's answer on new keyword

Another operator sizeof which returns std::size_t ( It does not actually need to include header, but my point here is that it uses an alias which is also defined in a header)

C++ §5.3.3

The result of sizeof and sizeof... is a constant of type std::size_t. [Note: std::size_t is defined in the standard header <cstddef>(18.2).— end note]

typeid use classes which are declared in <typeinfo> header

Header <typeinfo> synopsis

namespace std {
class type_info;
class bad_cast;
class bad_typeid;
}

See section 18.7 on iso cpp paper

IMO, Its C++ Standard Design Techniques, to keep the compiler neat, clean and lightweight



来源:https://stackoverflow.com/questions/33704978/why-do-i-need-to-include-typeinfo-when-using-the-typeid-operator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!