std::optional – removing confusion around pointer types

std::optional is a useful C++17 feature for knowing when a value is set. There’s been some debate however as to its usefulness for 2 forms.

1. std::optional<bool>
2. std::optional<T*>

Both forms are criticized for being confusing to readers. Considering that this post stems from having to explain recently what it means when std::optional wraps a pointer, I’m inclined to agree. The code below shows where the confusion lies:

std::optional<SomeDataType*> myval;
...
myval = nullptr;

if (myval)
// ?? Is this true or false?

In the highlightedline of the if statement, does will the value evaluate as true or false? It, in fact, does evaluate as true, and the value of operator bool is true. This is where the confusion is though. Some developers see std::optional as a simplified version of a wayt to wrap a pointer, similar to a smartptr. But it is quite different. In this case having set the value, even to nullptr, means the variable is “set”, so to speak. It may not sound very useful, but there are some cases, were knowing if a value is set, where nullptr is a valid value, is useful. The example below of a fast cache that shows that usefulness:

Continue reading std::optional – removing confusion around pointer types