§The Annotated C++ StandardC++ 标准注疏 中文
17.7

Type identification

std::type_info, the result type of typeid: == compares types rather than object addresses, and the results of before, hash_code and name are all unspecified or implementation-defined; plus bad_cast and bad_typeid, thrown when dynamic_cast and typeid fail.

Key points

  • std::type_info can only be produced by typeid, can't be copied, and can only be used through references or pointers; <typeinfo> must be included before use.
  • To check whether two types are the same, use ==; don't compare the addresses &typeid(T). Since C++23, == is constexpr.
  • The order of before, the value of hash_code and the contents of name are all unspecified or implementation-defined, may differ between programs, and can't be persisted or compared across processes. hash_code may collide.
  • A dynamic_cast to a reference type throws std::bad_cast on failure; typeid(*p) with p null and a polymorphic type throws std::bad_typeid.
  • To use types as container keys, use std::type_index.

The result of typeid#

C++type-info-eq.cpp✓ well-formedgodbolt ↗
#include <typeinfo>

static_assert(typeid(int) == typeid(const int));  // top-level cv is ignored
static_assert(typeid(int&) == typeid(int));       // so are references
static_assert(typeid(int) != typeid(long));

int main() {}

Run-time type identification (RTTI) has two entry points in the language: typeid ([expr.typeid]) and dynamic_cast ([expr.dynamic.cast]). typeid yields a const std::type_info lvalue describing a type; applied to an object of polymorphic type, it describes the object's dynamic type. This subclause defines type_info and the two exception classes that report failures.

¶1 [support.rtti.general] says <typeinfo> defines a type associated with type information generated by the implementation, and two types for reporting type identification errors; <typeindex> defines a wrapper type usable as a key in associative containers. <typeinfo> is entirely freestanding.

std::type_info isn't predefined. If no standard library declaration of std::type_info (by including <typeinfo> or by import std;) precedes a typeid expression, the program is ill-formed ([expr.typeid]/8). Clang 23's diagnostic is you need to include <typeinfo> or import std before using the 'typeid' operator.

type_info [type.info]#

C++
class type_info {
public:
  virtual ~type_info();
  constexpr bool operator==(const type_info& rhs) const noexcept;
  bool before(const type_info& rhs) const noexcept;
  size_t hash_code() const noexcept;
  const char* name() const noexcept;
  type_info(const type_info&) = delete;
  type_info& operator=(const type_info&) = delete;
};

This class has no public constructor and can't be copied. The object typeid returns lasts until the end of the program ([expr.typeid]/1), so storing a const type_info& or const type_info* is safe.

The destructor is virtual because implementations derive internal classes from type_info to hold the inheritance information dynamic_cast needs. The Itanium ABI has __class_type_info, __si_class_type_info (single inheritance), __vmi_class_type_info (multiple or virtual inheritance) and others, and the dynamic type of the object typeid returns may be any of them. != is obtained by rewriting == ([over.match.oper]).

The standard says

The names, encoding rule, and collating sequence for types are all unspecified and may differ between programs.

¶1 An object of type_info effectively stores a pointer to a name for the type and an encoded value for comparing types for equality or collating order. The names, encoding rule and collating sequence are all unspecified and may differ between programs. So the results of name(), hash_code() and before() shouldn't be written to files or sent to another process.

operator== (¶2–¶3)#

¶3 Returns true if the two type_info objects describe the same type. The standard only guarantees that type_info objects describing the same type compare equal; it doesn't guarantee that every typeid of the same type yields the same object. In practice the type information for a type may exist in several copies across shared libraries, so comparing &typeid(T) is unreliable.

How libc++ compares two type_infos

libc++'s <typeinfo> chooses one of three strategies per platform (the macro _LIBCPP_TYPEINFO_COMPARISON_IMPLEMENTATION):

  1. Unique (most ELF platforms): assumes the linker merges the type information for each type into a single copy, and compares only the addresses of the type name strings;
  2. NonUnique (Windows, AIX): equal if the addresses are equal or the string contents are equal;
  3. NonUniqueARMRTTIBit (Apple arm64, the platform we tested on): the compiler marks in the top bit of the name pointer whether this copy of the type information might not be unique; if both are unique, the addresses are compared, otherwise the strings.

Under the Unique strategy, if two shared libraries are both compiled with -fvisibility=hidden and each carries type information for some type, a cross-library comparison sees two different types, and cross-library dynamic_cast and catch fail as a result. This is a common deployment problem. The standard itself doesn't deal with shared libraries, so this isn't a violation of the standard but a trade-off the implementation makes at the ABI level.

before, hash_code, name (¶4–¶9)#

¶5 before returns true if *this precedes rhs in the implementation's collation order. This order has nothing to do with inheritance, declaration order or lexicographic order of names; it exists only so that types can be put in ordered containers, and type_index::operator< is implemented with it.

¶6 hash_code returns an unspecified value, guaranteeing only that, within a single execution of the program, two type_info objects that compare equal return the same value.

¶7 The implementation should return different values for two type_info objects that don't compare equal, but this is only a recommendation, and hash collisions are allowed. So hash_code() can't serve as a unique identifier for a type.

¶8 name returns an implementation-defined null-terminated byte string, and paragraph 9 adds that it may be a multibyte string suitable for conversion and display as a wstring. The standard has no other requirements on its contents; it doesn't even require different types to have different names.

C++type-name.cpp? implementation-definedgodbolt ↗
#include <cstdio>
#include <typeinfo>

struct Derived {};

int main() {
  std::printf("%s %s\n", typeid(int).name(), typeid(Derived).name());
}

GCC and Clang follow the Itanium ABI and return the part of the mangled name that represents the type; Clang 23 prints i 7Derived. You can restore a readable form with abi::__cxa_demangle from <cxxabi.h>. MSVC returns a readable name, such as class Derived. When you need a stable, portable type name, C++26 static reflection provides std::meta::identifier_of and std::meta::display_string_of ([expr.reflect]).

bad_cast and bad_typeid [bad.cast], [bad.typeid]#

C++rtti-errors.cpp✓ well-formedgodbolt ↗
#include <cstdio>
#include <typeinfo>

struct Base { virtual ~Base() = default; };
struct Derived : Base {};
struct Other : Base {};

int main() {
  Base* b = new Derived;
  Base* np = nullptr;
  try {
    (void)typeid(*np);              // null pointer: throws bad_typeid
  } catch (const std::bad_typeid&) {
    std::puts("bad_typeid");
  }
  try {
    (void)dynamic_cast<Other&>(*b); // failed conversion to a reference: throws bad_cast
  } catch (const std::bad_cast&) {
    std::puts("bad_cast");
  }
  delete b;
}

Both derive from std::exception, and what() returns an implementation-defined string; the conventions for the special member functions are in [exception].

bad_cast reports an invalid dynamic_cast ([bad.cast]). A failed dynamic_cast to a pointer type gives a null pointer; only a failed cast to a reference type throws. The standard library uses it elsewhere too: for example, std::use_facet throws bad_cast when the facet isn't found, and the bad_any_cast thrown by std::any_cast derives from it.

bad_typeid reports a null pointer in a typeid expression ([bad.typeid]).

Why typeid(*np) isn't undefined behavior

Dereferencing a null pointer is generally undefined behavior, but [expr.typeid]/3 specifically says: if the operand of typeid has the form *p (possibly parenthesized) and p is a null pointer, typeid throws bad_typeid. The condition is narrow. typeid(f(*p)) isn't protected; and when the type of *p isn't a polymorphic class, the operand isn't evaluated at all ([expr.typeid]/5), so there is no dereference and no exception, and the result is the type_info of the static type.

Questions#

Question

In what order does a std::map<std::type_index, int> iterate? Is the order guaranteed to be the same between two runs?

Answer

In the order of type_info::before ([type.index]/4). That order is unspecified ([type.info] paragraph 1) and may depend on the addresses of the type information, so it can change with link order or even address space randomization. When you need a stable order, maintain your own mapping from types to numbers.

In this clause

The authoritative text is eel.is/c++draft/support.rtti (working draft 2026-08-23, commit c7015b485c). These are study notes that explain rather than quote; ¶ numbers follow the draft. Translated from the Chinese original. Last updated 2026-10-19.