0
0
CppHow-ToBeginner · 3 min read

How to Use std::optional in C++: Syntax and Examples

Use std::optional<T> to represent a value that may or may not be present in C++. You can check if it contains a value with has_value() or by converting it to bool, and access the value with value() or * operator.
📐

Syntax

std::optional<T> is a template that holds either a value of type T or no value. You can create an empty optional or initialize it with a value. Use has_value() or operator bool() to check if it contains a value. Access the value with value() or *.

cpp
std::optional<T> opt;           // empty optional
std::optional<T> opt2 = value;  // optional with a value

if (opt.has_value()) {
    T val = opt.value();        // get the value safely
}

if (opt) {
    T val = *opt;               // get the value using operator*
}
💻

Example

This example shows how to create an optional, check if it has a value, and access the value safely.

cpp
#include <iostream>
#include <optional>

int main() {
    std::optional<int> maybeNumber;  // empty optional

    if (!maybeNumber) {
        std::cout << "No value yet\n";
    }

    maybeNumber = 42;  // assign a value

    if (maybeNumber.has_value()) {
        std::cout << "Value is: " << maybeNumber.value() << "\n";
    }

    // Using operator*
    std::cout << "Value using *: " << *maybeNumber << "\n";

    return 0;
}
Output
No value yet Value is: 42 Value using *: 42
⚠️

Common Pitfalls

  • Accessing the value without checking if it exists causes std::bad_optional_access exception.
  • Do not assume an optional always has a value; always check with has_value() or operator bool().
  • Assigning std::nullopt clears the optional.
cpp
std::optional<int> opt;
// Wrong: accessing value without checking
// int val = opt.value(); // throws exception

// Right way:
if (opt) {
    int val = opt.value();
} else {
    // handle no value case
}
📊

Quick Reference

OperationDescriptionExample
Create empty optionalOptional with no valuestd::optional opt;
Create with valueOptional initialized with a valuestd::optional opt = 10;
Check if has valueReturns true if value existsif (opt.has_value()) or if (opt)
Access valueGet the stored valueopt.value() or *opt
Reset optionalClear the valueopt = std::nullopt;

Key Takeaways

Use std::optional to safely represent values that may be missing.
Always check if an optional has a value before accessing it.
Access the value with value() or operator* after confirming presence.
Assign std::nullopt to clear an optional's value.
std::optional helps avoid unsafe null pointers and exceptions.