Library feature: std::optional

code

Syntax

std::optional behaves as a variant of a type T and the value std::nullopt.

We can set the value as we would do with any other type, but we can also assign it to std::nullopt – instead of returning nullptr, -1, 0, “”, or whatever we’d expect to receive in case an error occurs.

We can interogate the status of it by using the has_value() function, or directly access it through value(). Calling value when the optional is not set will throw a std::bad_optional_access exception. For performance reasons, using * and -> on it don’t throw an exception, but it IS undefined behavior.

std::make_optional

As our make_unique and make_shared constructs, make_optional will also contruct the object in-place.

Example of usage

 

Leave a comment

Your email address will not be published.