| Home | Libraries | People | FAQ | More

#### The semantics

Objects of type `optional<T>` are intended to be used in places where objects of type `T` would but which might be uninitialized. Hence, `optional<T>`'s purpose is to formalize the additional possibly uninitialized state. From the perspective of this role, `optional<T>` can have the same operational semantics of `T` plus the additional semantics corresponding to this special state. As such, `optional<T>` could be thought of as a supertype of `T`. Of course, we can't do that in C++, so we need to compose the desired semantics using a different mechanism. Doing it the other way around, that is, making `optional<T>` a subtype of `T` is not only conceptually wrong but also impractical: it is not allowed to derive from a non-class type, such as a built-in type.

We can draw from the purpose of `optional<T>` the required basic semantics:

- Default Construction: To introduce a formally uninitialized wrapped object.
- Direct Value Construction via copy: To introduce a formally initialized wrapped object whose value is obtained as a copy of some object.
- Deep Copy Construction: To obtain a new yet equivalent wrapped object.
- Direct Value Assignment (upon initialized): To assign a value to the wrapped object.
- Direct Value Assignment (upon uninitialized): To initialize the wrapped object with a value obtained as a copy of some object.
- Assignment (upon initialized): To assign to the wrapped object the value of another wrapped object.
- Assignment (upon uninitialized): To initialize the wrapped object with value of another wrapped object.
- Deep Relational Operations (when supported by the type T): To compare wrapped object values taking into account the presence of uninitialized states.
- Value access: To unwrap the wrapped object.
- Initialization state query: To determine if the object is formally initialized or not.
- Swap: To exchange wrapped objects. (with whatever exception safety guarantees are provided by `T`'s swap).
- De-initialization: To release the wrapped object (if any) and leave the wrapper in the uninitialized state.

Additional operations are useful, such as converting constructors and converting assignments, in-place construction and assignment, and safe value access via a pointer to the wrapped object or null.