在 C++17 之前,函数返回值通常要么是必定存在的对象,要么通过指针/引用或返回值包装(如 boost::optional)来表示“可能不存在”。随着 C++17 标准加入 std::optional,我们可以更简洁、安全地处理这种“可选值”的情况。本文将演示 std::optional 的基本使用、与异常的比较、以及如何与 STL 算法配合。
1. std::optional 简介
`std::optional
` 表示一个可容纳 `T` 类型对象的容器,且可能为空(无值)。它的核心语义是: – 当对象包含有效值时,`optional.has_value()` 为 `true`,可以通过 `operator*` 或 `value()` 访问。 – 当对象为空时,`has_value()` 为 `false`,访问 `value()` 会抛出 `std::bad_optional_access`。 “`cpp #include #include std::optional read_file(const std::string& path) { std::ifstream ifs(path); if (!ifs.is_open()) return std::nullopt; // 空值 std::stringstream buffer; buffer parse_int(const std::string& s) { try { return std::stoi(s); } catch (…) { return std::nullopt; } } “` ### 4. 与 STL 算法配合 `std::optional` 可以作为容器元素,或作为算法结果。利用 `std::transform`、`std::find_if` 等结合 `std::optional` 可以写出清晰的代码。 “`cpp std::vector strs = {“1”, “two”, “3”}; std::vector> nums; std::transform(strs.begin(), strs.end(), std::back_inserter(nums), [](const auto& s) { return parse_int(s); }); for (const auto& opt : nums) { if (opt) std::cout ` 也会移动构造。 – **`std::make_optional (args…)`**:在 C++17+ 可直接构造非空可选,避免多余复制。 ### 6. 结论 `std::optional` 是 C++17 提供的一个强大工具,帮助程序员显式表示“值可能不存在”的情况。相比异常,它更适合业务逻辑层面的可选值。掌握 `std::optional` 的基本用法后,能够写出更安全、可读性更高的代码。