Search⌘ K
AI Features

Representing Optional Values with std::optional

Explore how to use std optional in C++ to represent values that may or may not be present. Understand its syntax, memory usage, and advantages over pointers or null enums to write safer, more expressive code.

Let's begin by exploring std::optional and some of its important use cases.

Optional values with std::optional

Although quite a minor feature from C++17, std::optional is a nice addition to the standard library. It simplifies a common case that couldn’t be expressed cleanly and straightforwardly prior to std::optional. In a nutshell, it is a small wrapper for any type where the wrapped type can be either initialized or uninitialized.

To put it in C++ lingo, std::optional is a stack-allocated container with a max size of one.

Optional return values

Before the introduction of std::optional, there was no clear way to define functions that may not return a defined value, such as the intersection point of two line segments. With the introduction of std::optional, such optional return values can be clearly expressed. What ...