蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实测 C++17 多态动态 typeid、静态非多态对比及空指针 std::bad_typeid 异常

CPP本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。explore-cpp-libs-typeinfo.cpp
explore-cpp-libs-typeinfo.cpp123 行
#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;
}
本例需在 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。

入口文件:projects/cplusplus-cpp-libs-typeinfo-lab/explore-cpp-libs-typeinfo.cpp

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-cpp-libs-typeinfo.cpp,或下载右侧课程工程包。
  2. 确认本地已准备 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:C++

课程关联工程包(登记关联99章) · 含当前章节或实例 · mbskycom202612a2307.zip

下载课程关联工程包:C++

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2374.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习