Introduction

suggest change

Optionals (also known as Maybe types) are used to represent a type whose contents may or may not be present. They are implemented in C++17 as the std::optional class. For example, an object of type std::optional<int> may contain some value of type int, or it may contain no value.

Optionals are commonly used either to represent a value that may not exist or as a return type from a function that can fail to return a meaningful result.

Other approaches to optional

There are many other approach to solving the problem that std::optional solves, but none of them are quite complete: using a pointer, using a sentinel, or using a pair<bool, T>.

Optional vs Pointer

In some cases, we can provide a pointer to an existing object or nullptr to indicate failure. But this is limited to those cases where objects already exist - optional, as a value type, can also be used to return new objects without resorting to memory allocation.

Optional vs Sentinel

A common idiom is to use a special value to indicate that the value is meaningless. This may be 0 or -1 for integral types, or nullptr for pointers. However, this reduces the space of valid values (you cannot differentiate between a valid 0 and a meaningless 0) and many types do not have a natural choice for the sentinel value.

Optional vs std::pair<bool, T>

Another common idiom is to provide a pair, where one of the elements is a bool indicating whether or not the value is meaningful.

This relies upon the value type being default-constructible in the case of error, which is not possible for some types and possible but undesirable for others. An optional<T>, in the case of error, does not need to construct anything.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


std::optional:
* Introduction

Table Of Contents
8 Arrays
11 Loops
31 std::optional
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype