Module lessons (1/4)
Safe Types: std::optional and std::variant
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) withstd::optional<T>andstd::nullopt. - Extract data securely using
if (opt),.value_or(default)instead of*opton an optional blank. - Replace the unsafe
unionCs withstd::variant<T1, T2, ...>,std::get_if, andstd::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
- 11.
std::optional<T>: Value orstd::nullopton the Stack - 22.
*opt/.value()/.value_or()Comparison - 33.
std::variant<Ts...>: Union Type-Safe - 44. Exhaustive Dispatch with
std::visit - 5Practical exercises
- 6Check for understanding
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.