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

std::expected 是 C++23 中真正可用的“结果类型”,它比手动传 std::error_code* 或抛异常更轻量、更可控,但用错地方反而会让错误处理更混乱。
什么时候该用 std::expected 而不是异常?
适合明确区分“预期失败”和“意外崩溃”的场景:比如文件打开失败(路径不存在、权限不足)、网络请求返回 404/503、JSON 解析字段缺失——这些是业务逻辑中可预见、需分支处理的失败,不是程序 bug。
- 函数签名清晰暴露可能失败:
std::expected<:string std::errc></:string>比std::string+ 注释“失败时抛std::system_error”更可靠 - 调用方无法忽略错误:必须显式检查
.has_value()或用.value_or()/.and_then() - 避免异常开销或禁用异常环境(嵌入式、游戏引擎底层)
- 不适用于需要栈展开清理资源的场景(比如构造函数中途失败且持有 RAII 对象)
std::expected 的基本构造与取值方式
不能像 std::optional 那样默认构造成功值;必须显式指定成功或失败态。常见误区是误用 value() 导致未定义行为。
- 构造成功值:
std::expected<int std::errc>{42}</int>或std::make_expected_from_current_exception(42) - 构造失败值:
std::expected<int std::errc>{std::unexpect, std::errc::no_such_file_or_directory}</int> - 安全取值:
e.value_or(-1)(失败时返回默认值),e.has_value() ? e.value() : handle_error(e.error()) - 危险操作:
e.value()在e.has_value() == false时直接std::terminate,无异常抛出
auto read_config() -> std::expected<std::string, std::errc> {
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<char>{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) ... } 更紧凑,也避免忘记检查中间步骤。
立即学习“C++免费学习笔记(深入)”;
- 函数参数类型必须匹配:若
e是std::expected<t e></t>,则e.and_then(f)要求f签名为T → std::expected<u e></u>(错误类型必须一致) - 不支持跨错误类型转换,如需统一错误码,提前用
std::variant封装或转换为通用枚举 -
.map()仅转换成功值,不改变是否失败;.or_else()仅在失败时执行,用于 fallback 或日志
auto load_and_validate() {
return read_config()
.and_then([](std::string s) -> std::expected<Config, std::errc> {
auto cfg = parse_json(s);
if (!cfg.is_valid()) {
return std::unexpected{std::errc::invalid_argument};
}
return cfg;
})
.and_then([](Config c) -> std::expected<Config, std::errc> {
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<t std::errc></t>—— 标准错误码,零成本,适合系统调用封装 - 需要自定义错误信息时:
std::expected<t std::error_code></t>,但必须确保 category 全局存活(例如用std::generic_category()或静态注册的 category) - 避免
std::expected<t std::string></t>:无法参与错误分类、比较、国际化,且拷贝开销大 - 不要把
std::exception_ptr塞进expected:失去静态类型优势,又没获得异常的栈展开能力
最易被忽略的是错误类型的传播一致性:一旦在某个接口用了 std::expected<t myerrorenum></t>,下游所有 and_then 必须保持相同错误类型,否则编译失败。这不是缺陷,而是强制你提前设计错误域边界。











