您的位置:首页 >C++23 std::expected如何优雅处理函数错误?
发布于2026-02-12 阅读(0)
扫一扫,手机访问
std::expected 是 C++23 引入的值语义错误处理工具,本质是 std::variant<T, E> 的封装,适合替代错误码而非异常,用于需显式传播错误但禁用异常的场景(如嵌入式、系统调用),不适用于需栈展开或不可恢复错误。

std::expected 是 C++23 引入的值语义错误处理工具,本质是 std::variant<T, E> 的封装,其中 T 是成功值类型,E 是错误类型(通常为 std::error_code 或自定义错误枚举)。它既不抛异常,也不靠返回码隐式判断,而是把「结果」和「错误」都显式打包进一个对象里。
它适合替代「需要明确传播错误但又不想用异常」的场景,比如嵌入式、游戏引擎底层、系统调用封装、异步 I/O 回调链。不适合替代异常的场景:需要栈展开清理资源、错误不可恢复且应立即中止流程。
常见误用是把它当 bool 用——只检查 has_value() 就丢掉 error(),这等于把错误码又变回了“忽略型错误码”。
关键不是“怎么返回”,而是“怎么让调用方不用写一堆 if (!res.has_value())”。推荐组合使用 and_then(C++23)和手动解包逻辑。
and_then 接收一个 std::expected<U, E> (T&&) 形式的函数,自动在 has_value() == true 时调用,并透传错误;失败时直接短路返回原错误res.value() —— 它会 throw std::bad_expected_access,除非你确定已检查过error() 获取后做分支;对意外错误(如 std::errc::io_error),可转为 std::unreachable() 或日志后 abortstd::expected<int, std::errc> parse_int(std::string_view s) {
char* end;
long v = std::strtol(s.data(), &end, 10);
if (*end != '\0') return std::unexpected{std::errc::invalid_argument};
if (v < INT_MIN || v > INT_MAX) return std::unexpected{std::errc::result_out_of_range};
return static_cast<int>(v);
}
auto res = parse_int("42")
.and_then([](int i) -> std::expected<int, std::errc> {
if (i < 0) return std::unexpected{std::errc::invalid_argument};
return i * 2;
});
// res 是 std::expected<int, std::errc>,无需手动判空
std::expected<T, std::error_code> 是最常用组合,但容易踩三个坑:
std::make_error_code 构造泛型错误——它不保证跨编译单元唯一性;应统一用 std::errc 或自定义 std::error_categorystd::error_code 默认可隐式构造,导致 std::expected<int, std::error_code>{42} 编译通过,但其实是把 42 当作 error 构造了!务必显式用 std::expected<int, std::error_code>{std::in_place, 42} 或直接写 std::expected<int, std::error_code>{42} 仅当 T 可隐式转换自 int(不推荐)std::error_code 要用 ==,不是 .value() == —— 后者忽略 category,可能误判(例如 std::errc::no_such_file_or_directory 和 Windows 的 ERROR_FILE_NOT_FOUND 值相同但 category 不同)它不是银弹。以下情况建议退回更轻量或更重的方案:
std::optional<T> + 独立错误日志更简单std::variant<E1, E2, E3> 比 std::expected<T, E> 更灵活,但失去值语义一致性std::expected 会割裂错误处理风格,增加心智负担std::expected),注意其移动构造/赋值仍有开销,比纯 int 返回码重最常被忽略的一点:std::expected 的真正价值不在单个函数,而在整条调用链的错误透明传递。如果只有出口函数检查错误,中间全用 .value() 强解,那和裸指针解引用没区别——崩溃只是早晚问题。
上一篇:手机QQ加密聊天设置教程
下一篇:偃武S1赛季普射弓阵容搭配攻略
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9