Skip to main content
Module 10 · Lesson 1 of 423/26 in the course~16 min
Module lessons (1/4)

Safe Types: std::optional and std::variant

Lesson preview5 hands-on exercises readyCourse C++ · Module 10 — Modern Error Handling and Competition

Replace magic sentinels and insecure unions with std::optional<T>, std::nullopt, std::variant and std::visit.

What you'll learn in this lesson

  • Replace ambiguous sentinel values (-1, "", nullptr) with std::optional<T> and std::nullopt.
  • Extract data securely using if (opt), .value_or(default) instead of *opt on an optional blank.
  • Replace the unsafe union Cs with std::variant<T1, T2, ...>, std::get_if, and std::visit.

Overview

Until C++14, a potentially failing search function would often return -1, nullptr (requiring Heap allocation), or std::pair<bool, T> pairs. Since C++17, <optional> and <variant> express the optional presence and algebraic sums on the Stack directly in the type!

std::optional<int> reserves Stack space for a int plus an internal boolean flag, without any dynamic allocation:

Sections covered in this lesson

  1. 11. std::optional<T>: Value or std::nullopt on the Stack
  2. 22. *opt / .value() / .value_or() Comparison
  3. 33. std::variant<Ts...>: Union Type-Safe
  4. 44. Exhaustive Dispatch with std::visit
  5. 5Practical exercises
  6. 6Check for understanding
Pro Lesson · Module 10 — Modern Error Handling and Competition

Unlock "Safe Types: std::optional and std::variant" and the full Course C++ curriculum

Replace magic sentinels and insecure unions with std::optional<T>, std::nullopt, std::variant and std::visit.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course C++ plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.