You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何std::typeid解引用char空指针时不抛出bad_typeid异常?

std::typeid处理空指针的行为差异解析

先看示例代码:

#include <typeinfo>
#include <iostream>
using namespace std;
class Test
{
    public:
    Test(){}
    virtual ~Test(){}
};
int main()
{
    Test *ptrvar = nullptr;
    char* cptr = nullptr;
    try 
    {
        cout << typeid(*cptr).name() << endl;
        cout << typeid(*ptrvar).name() << endl;
    }
    catch (bad_typeid) 
    {
        cout << "The object is null" << endl;
    }
    return 0;
}

程序输出:

c
The object is null

核心原因拆解

  • 基本类型(如char)的情况:
    char属于非多态类型,std::typeid处理这类类型时,编译阶段就能确定*cptr的静态类型是char,完全不需要在运行时去解引用空指针或者访问内存中的对象数据。哪怕指针是空的,typeid直接返回编译期就确定好的char类型信息,不会触发任何异常。

  • 带虚函数的Test类情况:
    包含虚函数的类属于多态类型,std::typeid对多态类型对象操作时,需要获取它的运行时实际类型——这个信息存储在对象的虚函数表(vtable)中。但空指针指向的内存区域根本不存在合法的Test对象,自然也没有可读取的虚函数表。此时typeid无法获取有效类型信息,就会抛出bad_typeid异常。

内容的提问来源于stack exchange,提问作者Hardik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 22:05:22