You need to enable JavaScript to run this app. C++构造函数调用虚函数问题:自定义异常类自动打日志有没有更好方案?
优惠活动
大模型
产品
解决方案
定价
更多

C++构造函数调用虚函数问题:自定义异常类自动打日志有没有更好方案?

方案1:调整基类存储异常信息,消除虚函数依赖

该方案适配绝大多数what()返回固定字符串的场景,改动量最小,完全规避构造期虚函数调用问题:
首先修改基类CPPException:

class CPPException {
    const char* source = nullptr;
    const char* _what = nullptr; // 新增成员存储异常描述
public:
    // 构造函数新增what参数,初始化完成后直接打印日志
    CPPException(const char* src, const char* what_str) 
        : source(src), _what(what_str) {
        LogException();
    }
    CPPException(void) = delete;
    ~CPPException() = default;

    // 改为非虚函数,直接返回成员变量
    const char* what() const { return _what; }
    const char* where() const { return source; }
    void LogException() const {
        Logger::LogError(R"(Got a CPP Exception in "%s" : %s)", where(), what());
    }
};

子类实现可直接简化为以下形式,无需再手动调用LogException:

class BadAlloc : public CPPException {
public:
    BadAlloc(const char* src) : CPPException(src, "bad alloc") {}
};

// 其他子类仅需传入对应的固定异常描述即可
class OutOfRange : public CPPException {
public:
    OutOfRange(const char* src) : CPPException(src, "out of range") {}
};

方案2:CRTP中间层适配动态异常描述场景

如果存在需要动态生成what()返回内容的子类(比如带错误参数的异常),可以用奇异递归模板模式做中间层,绕过基类构造期虚表未初始化的问题:

class CPPException {
    const char* source = nullptr;
    bool logged = false; // 新增标记避免拷贝异常时重复打印日志
public:
    CPPException(const char* src) : source(src) {}
    CPPException(void) = delete;
    virtual ~CPPException() = default;

    virtual const char* what() const = 0;
    const char* where() const { return source; }
    
    void LogException() const {
        if (!logged) {
            Logger::LogError(R"(Got a CPP Exception in "%s" : %s)", where(), what());
            logged = true;
        }
    }
};

// CRTP中间层
template<typename Derived>
class CPPExceptionImpl : public CPPException {
public:
    explicit CPPExceptionImpl(const char* src) : CPPException(src) {
        // 此时派生类虚表已初始化完成,调用的是派生类的what实现
        static_cast<const Derived*>(this)->LogException();
    }
};

子类实现示例:

// 固定描述的异常
class BadAlloc : public CPPExceptionImpl<BadAlloc> {
public:
    using CPPExceptionImpl<BadAlloc>::CPPExceptionImpl;
    const char* what() const override { return "bad alloc"; }
};

// 动态生成描述的异常
class InvalidIndex : public CPPExceptionImpl<InvalidIndex> {
    char buf[64]{};
public:
    InvalidIndex(const char* src, int idx) : CPPExceptionImpl(src) {
        snprintf(buf, sizeof(buf), "invalid index %d", idx);
    }
    const char* what() const override { return buf; }
};

补充说明

你之前尝试直接读取虚表调用的方案本质是未定义行为:基类构造执行阶段,对象的虚表指针仅指向基类的虚表,派生类的虚表还未完成赋值,不可能拿到派生类的what实现,完全不推荐这类hack操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 02:12:05