Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::optional

Use case

Return value that may or may not exist.

Explanation

std::optional<T> holds either a value or nothing. Cleaner than returning sentinel values or pointers.

Code

#include <cstdint>
#include <iostream>
#include <optional>

std::optional<uint64_t> findSymbol(const char *name) {
  if (name[0] == '_') {
    return 0x10001000;
  }
  return std::nullopt;
}

int main() {
  if (auto addr = findSymbol("_main")) {
    std::cout << "Found: 0x" << std::hex << *addr << "\n";
  }

  auto missing = findSymbol("invalid");
  std::cout << "Default: 0x" << missing.value_or(0) << "\n";
  return 0;
}

View on GitHub.

Output

$ ./src/c++17/build/std-optional
Found: 0x10001000
Default: 0x0