贝利信息

c++如何使用std::expected处理错误_c++ 23返回值与错误码封装【方法】

日期:2025-12-30 00:00 / 作者:冰火之心
std::expected适用于可预见的业务失败场景,如文件打开失败、网络请求错误等,需显式处理而非异常;构造须指定成功/失败态,取值应避免直接调用value()以防终止。

std::expected 是 C++23 中真正可用的“结果类型”,它比手动传 std::error_code* 或抛异常更轻量、更可控,但用错地方反而会让错误处理更混乱。

什么时候该用 std::expected 而不是异常?

适合明确区分“预期失败”和“意外崩溃”的场景:比如文件打开失败(路径不存在、权限不足)、网络请求返回 404/503、JSON 解析字段缺失——这些是业务逻辑中可预见、需分支处理的失败,不是程序 bug。

std::expected 的基本构造与取值方式

不能像 std::optional 那样默认构造成功值;必须显式指定成功或失败态。常见误区是误用 value() 导致未定义行为。

auto read_config() -> std::expected {
    std::ifstream f{"config.json"};
    if (!f.is_open()) {
        return std::unexpected{std::errc::no_such_file_or_directory};
    }
    std::string content{std::istreambuf_iterator{f}, {}};
    return content;
}

// 使用
auto result = read_config();
if (result) {
    parse_json(result.value());
} else {
    std::cerr << "Config load failed: " 
              << std::make_error_code(result.error()).message() << "\n";
}

链式调用:用 .and_then() 替代嵌套 if

.and_then() 接收一个返回 std::expected 的函数,自动短路失败路径;比手写 if (ok) { auto r2 = f2(); if (r2) ... } 更紧凑,也避免忘记检查中间步骤。

auto load_and_validate() {
    return read_config()
        .and_then([](std::string s) -> std::expected {
            auto cfg = parse_json(s);
            if (!cfg.is_valid()) {
                return std::unexpected{std::errc::invalid_argument};
            }
            return cfg;
        })
        .and_then([](Config c) -> std::expected {
            if (!c.has_required_field()) {
                return std::unexpected{std::errc::state_not_recoverable};
            }
            return c;
        });
}

与旧式错误码(std::error_code)的互操作要点

std::expected 不自动兼容 std::error_code;它的错误类型是模板参数,需显式选择。用 std::errc 最轻量,但缺乏自定义上下文;用 std::error_code 需注意 category 生命周期。

最易被忽略的是错误类型的传播一致性:一旦在某个接口用了 std::expected,下游所有 and_then 必须保持相同错误类型,否则编译失败。这不是缺陷,而是强制你提前设计错误域边界。