C++ Introduction


Example

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.