cpp/utility/optional

The class template manages an optional contained value, i.e. a value that may or may not be present.

A common use case for is the return value of a function that may fail. As opposed to other approaches, such as, handles expensive-to-construct objects well and is more readable, as the intent is expressed explicitly.

Any instance of at any given point in time either contains a value or does not contain a value.

If an contains a value, the value is guaranteed to be allocated as part of the  object footprint, i.e. no dynamic memory allocation ever takes place. Thus, an object models an object, not a pointer, even though operator* and operator-> are defined.

When an object of type is contextually converted to, the conversion returns  if the object contains a value and  if it does not contain a value.

The object contains a value in the following conditions:


 * The object is initialized with/assigned from a value of type or another  that contains a value.

The object does not contain a value in the following conditions:


 * The object is default-initialized.
 * The object is initialized with/assigned from a value of type std or an  object that does not contain a value.
 * The member function reset is called.

There are no optional references; a program is ill-formed if it instantiates an with a reference type. Alternatively, an of a std of type  may be used to hold a reference. In addition, a program is ill-formed if it instantiates an with the (possibly cv-qualified) tag types std or std.