Skip to content

std::optional (C++17)

In a Nutshell

A container used to represent "a value that may not exist," which is safer and more intuitive than returning a status code plus a pointer or using output parameters.

Header File

<optional>

Core API Cheat Sheet

OperationSignatureDescription
Constructoptional()Default constructor, does not contain a value
Assign emptyreset() or = nulloptSets the state to valueless
Check has valuehas_value()Returns true if a value is present
Check has valueoperator bool()Same as above
Get valueoperator*() or operator->()Dereference to get value (undefined behavior if no value)
Safe getvalue()Get value, throws bad_optional_access if no value
Value or defaultvalue_or()Returns value if present, otherwise returns default value
In-place constructemplace()Constructs value in-place
Resetreset()Destroys the contained value

Minimal Example

Expand (25 lines)Collapse
cpp
#include <optional>
#include <iostream>

// A function that might fail
std::optional<int> divide(int a, int b) {
    if (b == 0) {
        return std::nullopt; // Indicate failure
    }
    return a / b; // Indicate success
}

int main() {
    auto result = divide(10, 2);

    // Check if result contains a value
    if (result) {
        std::cout << "Result: " << *result << '\n';
    } else {
        std::cout << "Division failed\n";
    }

    // Get value or default
    auto safe_result = divide(10, 0).value_or(-1);
    std::cout << "Safe result: " << safe_result << '\n';
}

Embedded Applicability: High

  • Zero-overhead abstraction; when no value is present, it only occupies storage space equivalent to one byte (plus alignment/padding), and involves no heap allocation.
  • Can replace raw pointers as return values for functions that may fail, avoiding the risks of null pointer dereferencing.
  • Fully supported since C++17; member functions are comprehensively constexpr in C++23 and later, further broadening the range of applicable scenarios.

Compiler Support

GCCClangMSVC
TBDTBDTBD

See Also


部分内容参考自 cppreference.com,采用 CC-BY-SA 4.0 许可

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05