...

/

Representing Optional Values with std::optional

Representing Optional Values with std::optional

Learn to use std::optional for optional values, returns, member variables, enums, sorting, and comparisons.

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 ...