C++ <typeinfo>
详解 C++ 运行时类型识别(RTTI)头文件 <typeinfo>、std::type_info 接口成员、typeid 运算符对多态与非多态表达式的差异以及 std::bad_typeid 异常与工程注意事项。
学完这一章,你能够
- 详解 C++ 运行时类型识别(RTTI)头文件 <typeinfo>、std::type_info 接口成员、typeid 运算符对多态与非多态表达式的差异以及 std::bad_typeid 异常与工程注意事项。
RTTI 运行时类型识别与 std::type_info 核心接口
`<typeinfo>` 头文件为 C++ 提供运行时类型识别(RTTI,Run-Time Type Identification)支持,核心由 **`std::type_info`** 类与 **`typeid`** 运算符组成,同时还声明了 `std::bad_cast` 与 `std::bad_typeid` 异常类。每个类型都关联一个静态存储期的 `const std::type_info` 对象;准确而言,`std::type_info` 并非含纯虚函数的抽象基类,而是禁止默认构造与拷贝/赋值的类型描述符,只能通过 `typeid` 运算符获取其常引用。
`std::type_info` 的常用只读成员函数包括:`const char* name() const noexcept;` 返回依赖编译器实现的类型名 C 字符串(例如 GCC/Itanium ABI 返回修饰名 `7Derived`,并非跨平台统一的可读名);`bool before(const std::type_info& rhs) const noexcept;` 给出实现定义的严格弱序用于排序或键比较;`operator==` 与 `operator!=` 判断两个 `type_info` 对象是否代表同一类型;此外自 C++11 起还提供 `size_t hash_code() const noexcept;` 以便配合 `std::type_index` 放入哈希容器。
typeid 运算符:静态类型与多态动态类型解析
`typeid` 运算符支持两种形态:`typeid(T)` 直接查询类型 `T` 的 `std::type_info`(自动忽略顶层 `const`/`volatile` 及引用修饰);`typeid(expr)` 查询表达式类型。当 `expr` 是**多态类类型**(包含至少一个虚函数)的泛左值(如解引用基类指针 `*basePtr`)时,`typeid` 在运行期通过虚表查询对象的实际动态类型,且若指针为空则抛出 `std::bad_typeid`;若表达式为非多态类型,`typeid` 在编译期即确定静态类型且不会对表达式求值。
在经典多态示例中,定义包含虚函数 `show()`(及建议配备虚析构函数 `virtual ~Base()` 以免经由基类指针 `delete` 时产生未定义行为)的 `Base` 与派生类 `Derived`。当 `Base* basePtr = new Derived();` 与 `Base* basePtr2 = new Base();` 时,`typeid(*basePtr) == typeid(Derived)` 为真、`typeid(*basePtr2) == typeid(Base)` 为真,且二者 `name()` 分别输出编译器对应的类型标识。
RTTI 使用注意事项与性能权衡
使用 `<typeinfo>` 与 RTTI 需牢记三点工程约束:其一,`type_info::name()` 格式高度依赖编译器(GCC 修饰名需配合 `abi::__cxa_demangle` 解码,MSVC 返回人类可读名),切勿将 `name()` 字符串硬编码到跨平台业务逻辑中;其二,动态 `typeid` 与 `dynamic_cast` 会带来虚表元数据占用与运行期检查开销;其三,只有具备虚函数的多态类才会触发运行期动态类型识别,常规场景应优先使用虚函数多态派发,仅在序列化、调试诊断或安全向下转型等确有需要时谨慎使用 RTTI。
实测 C++17 多态动态 typeid、静态非多态对比及空指针 std::bad_typeid 异常
展开查看收起
#include <cstdio>
#include <cstring>
#include <iostream>
#include <memory>
#include <string>
#include <typeinfo>
#include <vector>
namespace lab {
struct Case {
std::string name;
std::string expected_json;
std::string actual_json;
bool passed;
};
std::string esc(const std::string& s) {
std::string out = "\"";
for (unsigned char c : s) {
switch (c) {
case '\"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (c < 0x20) {
char buf[8];
std::snprintf(buf, sizeof(buf), "\\u%04x", c);
out += buf;
} else {
out += static_cast<char>(c);
}
}
}
out += "\"";
return out;
}
std::string jbool(bool v) { return v ? "true" : "false"; }
void emit(const std::vector<Case>& cases) {
std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
for (std::size_t i = 0; i < cases.size(); ++i) {
if (i) std::cout << ", ";
std::cout << "{\"name\": " << esc(cases[i].name)
<< ", \"expected\": " << cases[i].expected_json
<< ", \"actual\": " << cases[i].actual_json
<< ", \"passed\": " << jbool(cases[i].passed) << "}";
}
std::cout << "]}\n";
}
} // namespace lab
namespace {
class Base {
public:
virtual ~Base() = default;
virtual int kind() const { return 1; }
};
class Derived : public Base {
public:
int kind() const override { return 2; }
};
struct PlainBase {
int x = 0;
};
struct PlainDerived : PlainBase {
int y = 1;
};
} // namespace
int main() {
std::vector<lab::Case> cases;
// Case 1: Polymorphic RTTI with typeid and std::type_info methods
std::unique_ptr<Base> p1 = std::make_unique<Derived>();
std::unique_ptr<Base> p2 = std::make_unique<Base>();
const std::type_info& ti1 = typeid(*p1);
const std::type_info& ti2 = typeid(*p2);
bool order_asymmetric = (ti1.before(ti2) != ti2.before(ti1)) && !ti1.before(ti1);
bool poly_ok =
(ti1 == typeid(Derived)) &&
(ti2 == typeid(Base)) &&
(ti1 != ti2) &&
(ti1.hash_code() == typeid(Derived).hash_code()) &&
(std::strlen(ti1.name()) > 0) &&
(std::strlen(ti2.name()) > 0) &&
order_asymmetric;
cases.push_back({"polymorphic_typeid_dynamic", lab::jbool(true), lab::jbool(poly_ok), poly_ok});
// Case 2: Static typeid on cv-qualified types and non-polymorphic hierarchy
PlainDerived pd;
PlainBase* pb = &pd;
bool static_ok =
(typeid(int) == typeid(const int)) &&
(typeid(int) == typeid(int&)) &&
(typeid(*pb) == typeid(PlainBase)) &&
(typeid(*pb) != typeid(PlainDerived));
cases.push_back({"static_typeid_and_non_polymorphic", lab::jbool(true), lab::jbool(static_ok), static_ok});
// Case 3: Dereferencing null polymorphic pointer in typeid throws std::bad_typeid
Base* null_poly = nullptr;
bool caught_bad_typeid = false;
try {
const char* nm = typeid(*null_poly).name();
(void)nm;
} catch (const std::bad_typeid& e) {
caught_bad_typeid = (std::strlen(e.what()) > 0);
}
cases.push_back({"null_polymorphic_bad_typeid", lab::jbool(true), lab::jbool(caught_bad_typeid), caught_bad_typeid});
lab::emit(cases);
return 0;
}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
结果为 `false`。因为 `Base` 不是多态类型,`typeid(*p)` 在编译期直接返回静态类型 `Base` 的 `type_info`,不会在运行期查询动态类型。