Skip to content

std::optional (C++17)

One-Liner

A container that represents "a value may not exist," which is safer and more intuitive than returning a raw pointer or using an output parameter.

#include <optional>

Core API Quick Reference

OperationSignatureDescription
Constructoptional()Default construct, 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
Get valueT& operator*()Dereferences to get the value (undefined behavior if no value is present)
Safe getT& value()Gets the value, throws bad_optional_access if no value is present
Get or defaultT value_or(const T& default_value) constReturns the value if present, otherwise returns the default value
In-place constructT& emplace(Args&&... args)Constructs the value in-place
Resetvoid reset() noexceptDestroys the contained value

Minimal Example

cpp
#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

  • A zero-overhead abstraction; when no value is present, it only occupies storage the size of one bool, with no heap allocation involved
  • Can replace raw pointers as function return values for operations that might fail, avoiding the risk of null pointer dereferences
  • Fully supported since C++17, and member functions are comprehensively constexpr starting in C++23, further broadening its use cases

Compiler Support

GCCClangMSVC
TBATBATBA

See Also


Some content referenced from cppreference.com, licensed under CC-BY-SA 4.0

Built with VitePress