0Pricing
C++ Academy · Lesson

Accessing optional Values

Use value_or and has_value.

Dereference Operator

The fastest way to read an optional is *opt, but only when you are sure it holds a value, there is no check.

#include <iostream>
#include <optional>
int main() {
    std::optional<int> o = 10;
    if (o) std::cout << *o << "\n";
}

The value() Method

opt.value() returns the value, but throws std::bad_optional_access if the optional is empty. Use it when an empty optional is a real error.

#include <iostream>
#include <optional>
int main() {
    std::optional<int> o;
    try { std::cout << o.value() << "\n"; }
    catch (const std::bad_optional_access&) { std::cout << "empty!\n"; }
}

All lessons in this course

  1. Representing Absence with optional
  2. Accessing optional Values
  3. std::expected Basics
  4. Error Handling Patterns
← Back to C++ Academy