C++ typeid 的求值开关:同样包着函数调用,为什么有时根本不会执行

10-06 7阅读

在调试语句中把函数调用放进typeid,可能发现函数没有执行;换成返回多态对象引用的函数,计数又增加了。typeid是否求值取决于操作数的类型和表达式类别。只有“多态类类型的glvalue”这组条件满足时,才需要沿着表达式取得对象的动态类型。

C++ typeid 的求值开关:同样包着函数调用,为什么有时根本不会执行

AI模型生成的概念插图:一只盒子保持关闭,另一只打开后显示内部物件,用于比喻静态识别与实际求值;不是编译器执行截图。

完整复现与实际输出

将下面整段保存为demo.sh,运行bash demo.sh。需要Bash和支持C++20的g++;本次实跑为Linux上的g++ (Debian 14.2.0-19) 14.2.0。脚本只使用新建的私有临时目录,退出自动清理;正常构建后再用UBSan重跑并比较结果。

#!/usr/bin/env bash
set -euo pipefail
work=$(mktemp -d)
trap 'rm -rf -- "$work"' EXIT
cat > "$work/main.cpp" <<'CPP'
#include <cassert>
#include <iostream>
#include <typeinfo>

struct Plain {};
struct Base { virtual ~Base() = default; };
struct Derived : Base {};
int plain_calls = 0;
int reference_calls = 0;
int value_calls = 0;
Plain make_plain() { ++plain_calls; return {}; }
Base& get_reference() {
    ++reference_calls;
    static Derived object;
    return object;
}
Base make_value() { ++value_calls; return {}; }

int main() {
    std::cout << std::boolalpha;
    bool plain_type = typeid(make_plain()) == typeid(Plain);
    assert(plain_type && plain_calls == 0);
    std::cout << "nonpolymorphic call: calls=" << plain_calls
              << " Plain=" << plain_type << '\n';
    bool dynamic_type = typeid(get_reference()) == typeid(Derived);
    assert(dynamic_type && reference_calls == 1);
    std::cout << "polymorphic glvalue: calls=" << reference_calls
              << " Derived=" << dynamic_type << '\n';
    bool static_type = typeid(make_value()) == typeid(Base);
    assert(static_type && value_calls == 0);
    std::cout << "polymorphic prvalue: calls=" << value_calls
              << " Base=" << static_type << '\n';

    Plain* plain_null = nullptr;
    assert(typeid(*plain_null) == typeid(Plain));
    std::cout << "nonpolymorphic null operand: Plain=true\n";
    Base* polymorphic_null = nullptr;
    try {
        (void)typeid(*polymorphic_null);
        assert(false);
    } catch (const std::bad_typeid&) {
        std::cout << "polymorphic null operand: bad_typeid\n";
    }
}
CPP
g++ -std=c++20 -O0 -Wall -Wextra -pedantic "$work/main.cpp" -o "$work/demo"
"$work/demo"
g++ -std=c++20 -O1 -g -fsanitize=undefined -fno-sanitize-recover=all "$work/main.cpp" -o "$work/ubsan"
"$work/ubsan" > "$work/ubsan.out"
"$work/demo" > "$work/normal.out"
cmp "$work/normal.out" "$work/ubsan.out"
printf '%s\n' 'UBSan: same output, no diagnostic'

以下是完整脚本的实际标准输出。UBSan一行是两次结果比对成功后的脚本提示。

nonpolymorphic call: calls=0 Plain=true
polymorphic glvalue: calls=1 Derived=true
polymorphic prvalue: calls=0 Base=true
nonpolymorphic null operand: Plain=true
polymorphic null operand: bad_typeid
UBSan: same output, no diagnostic

普通类型的函数调用留在未求值位置

make_plain正文会增加plain_calls,但把它放在typeid内,输出计数仍为零,比较结果却已经确认Plain。这里根据表达式的静态类型即可得出结果,操作数不被求值。它不是“先调用,再丢掉返回值”,也不是优化器看见无用结果后碰巧省略了调用;带有可观察计数的正文仍然没有运行。

返回多态引用时,需要真正找到对象

Base具有虚析构函数,因此是多态类;get_reference返回Base引用,调用表达式是glvalue。typeid需要观察该引用实际指向的最派生对象,于是执行函数,计数变为一,比较得到Derived。程序没有按实现相关的type_info名称字符串判断类型,而是直接与typeid(Derived)比较。

只有多态类型仍不够,还要看值类别

make_value也返回Base,但按值返回的调用表达式是prvalue,不属于上一段的glvalue条件。第三行因此得到静态Base,value_calls仍为零。这一控制组阻止把规则简写成“有虚函数就会执行”。glvalue包括左值和将亡值;本例的引用返回使用的是其中最直观的左值情况。

未求值不代表随便什么语句都能通过

编译器仍要检查表达式在这个语境里是否合法,也要知道需要的类型。本文把全部类定义完整,并给Base保留公开可访问的析构函数。不能把不会调用误解为无需声明函数、无需满足类型规则,或者用它掩盖本来就不合法的表达式。

空指针实验只使用typeid规定的特殊形式

普通Plain指针为空时,typeid里的解引用表达式仍处于未求值语境,类型比较成功;多态Base空指针则在typeid的对应检查中抛bad_typeid。代码刻意只演示直接以星号作用于指针的形式,没有先建立一个空引用,更没有在typeid外访问对象成员。这个特例不能变成“空指针解引用可以放心试”的一般规则。

调试探针也要说明是否会触发业务动作

若函数会读取文件、移动游标或更新状态,把它包进typeid并不统一地保留或消除这些行为。安全排查方式是先看返回类型,再确认表达式类别;必要时先显式执行并保存结果,再检查那个已知对象。本文没有涉及对象构造或析构期间的特殊动态类型规则,也未关闭RTTI,结论只针对完整普通对象和展示的表达式。

参考资料

规则与链接核验于2026年10月5日。资料为C++公开工作草案;实验固定使用C++20模式,不依赖草案新增接口。输出只覆盖展示样本,UBSan无诊断不等于对任意扩展代码的安全保证。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。