std::expected 提供类型安全、无异常开销的错误处理,强制调用者处理成功与失败情况。1. 使用值类型 T 和轻量错误类型 E;2. 通过 and_then、or_else 链式组合操作;3. 包装旧接口实现平滑迁移,提升代码健壮性。

在C++23中,std::expected 提供了一种更清晰、更安全的方式来处理可能失败的操作。相比传统的异常抛出或返回错误码,它让调用者明确意识到“这个函数可能会失败”,并强制处理成功与失败两种情况,从而写出更健壮的代码。
传统做法如返回 bool + 输出参数、全局 errno 或抛出异常,都有明显缺点:bool 容易被忽略;errno 不够类型安全;异常可能被遗漏且影响性能。而 std::expected
将 std::expected 作为函数返回值时,应遵循以下原则:
1. 正确选择 T 和 E 类型
立即学习“C++免费学习笔记(深入)”;
enum class ParseError {
InvalidFormat,
Overflow
};
<p>std::expected<int, ParseError> parse_int(const std::string& str);</p>2. 提供清晰的错误构造方式
可以定义辅助函数或工厂函数来简化错误创建:
struct FileError {
int code;
std::string message;
<pre class='brush:php;toolbar:false;'>static auto not_found(const std::string& path) {
return FileError{404, "File not found: " + path};
}};
3. 使用 if-const-auto 检查结果
推荐写法:
auto result = parse_int("123");
if (result) {
std::cout << "Parsed: " << *result << "\n";
} else {
handle_error(result.error());
}
利用 and_then 和 or_else 可以优雅地串联多个可能失败的操作:
std::expected<std::string, FileError> read_file(const std::string& path);
std::expected<Json, ParseError> parse_json(std::string);
<p>// 组合读取并解析 JSON
auto data = read_file("config.json")
.and_then([](std::string s) { return parse_json(s); })
.or_else([](const FileError& e) {
log_error("Read failed: ", e.message);
return std::unexpected(ParseError::InvalidFormat);
});</p>这种风格避免了深层嵌套判断,使逻辑更线性、可读性更强。
在混合使用旧接口时,可用包装函数平滑迁移:
// 老式 C API
int legacy_divide(int a, int b, int* out);
<p>// 包装为 expected
std::expected<int, std::string> safe_divide(int a, int b) {
int result;
if (int err = legacy_divide(a, b, &result); err != 0) {
return std::unexpected("Division failed");
}
return result;
}</p>基本上就这些。使用 std::expected 的关键是改变思维模式:把错误当作一等公民来设计接口,而不是事后补救。它特别适合解析、I/O、配置加载等常见易错场景。只要坚持正确使用,就能显著提升代码的可靠性和可维护性。
以上就是C++如何优雅处理错误_C++23 std::expected作为函数返回值的最佳实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号