Skip to content

std::optional (C++17) ​

In a Nutshell ​

A container for representing "a value that may not exist" — safer and more intuitive than returning a bool plus a pointer or an output parameter.

#include <optional>

Core API Cheat Sheet ​

OperationSignatureDescription
Constructoptional()Default construction; contains no value
Assign emptyoptional& operator=(nullopt_t)Sets the state to no value
Check for valueexplicit operator bool() constReturns true when a value is present
Check for valuebool has_value() constSame as above
Access valueT& operator*()Dereferences to obtain the value (undefined behavior when there is no value)
Safe accessT& value()Returns the value; throws bad_optional_access if there is none
Value or defaultT value_or(const T& default_value) constReturns the value if present, otherwise the default value
In-place constructT& emplace(Args&&... args)Constructs the value in place
Resetvoid reset() noexceptDestroys the contained value

Minimal Example ​

C++
#include <iostream>
#include <optional>
#include <string>

std::optional<std::string> find(bool b) {
    return b ? std::optional<std::string>{"found"} : std::nullopt;
}

int main() {
    auto res = find(false);
    std::cout << res.value_or("not found") << '\n';

    if (auto val = find(true))
        std::cout << *val << '\n';
}

Embedded Applicability: High ​

  • Zero-overhead abstraction: the no-value state takes up only a bool-sized amount of storage, and no heap allocation is involved
  • Can replace raw pointers as the return type of functions that might fail, avoiding the risk of dereferencing a null pointer
  • Fully supported since C++17; member functions become fully constexpr from C++23 onward, further widening the range of applicable scenarios

Compiler Support ​

GCCClangMSVC
TBDTBDTBD

See Also ​


Some content is adapted from cppreference.com, used under the CC-BY-SA 4.0 license

pdf-latest-4-g85128cc · 85128cc · 2026-10-05