Jan*_*tke 8 c++ error-handling exception c++23 std-expected
我什么时候应该使用std::expected异常?什么时候应该使用异常?以这个函数为例:
int parse_int(std::string_view str) {
if (str.empty()) {
throw std::invalid_argument("string must not be empty");
}
/* ... */
if (/* result too large */) {
throw std::out_of_range("value exceeds maximum for int");
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
我想在使用此函数时区分不同的错误,因此抛出不同类型的异常很有用。但是,我也可以这样做std::expected:
enum class parse_error {
empty_string,
invalid_format,
out_of_range
};
std::expected<int, parse_error> parse_int(std::string_view str) noexcept {
if (str.empty()) {
return std::unexpected(parse_error::empty_string);
}
/* ... */
if (/* result too large */) {
return std::unexpected(parse_error::out_of_range);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
是否有任何理由使用std::expected异常(性能、代码大小、编译速度、ABI),或者只是风格偏好?
| 归档时间: |
|
| 查看次数: |
697 次 |
| 最近记录: |