ISO/IEC JTC1 SC22 WG21 N3406 = 12-0096 - 2012-09-20
Fernando Cacciola, fernando.cacciola@gmail.com Andrzej Krzemieński, akrzemi1@gmail.comClass template optional<T>
proposed here is a nullable type T
that can store in its storage space either a value of type T
or a special value nullopt
. Its interface allows to query whether a value of T
or nullopt
is currently stored. The interface is based on Fernando Cacciola's
Boost.Optional library[2], shipping since March, 2003, and widely used. It requires no changes to core language, and breaks no existing code.
Changes since N1878=05-0138:
nullopt
instead of nullptr
to indicate the 'disengaged' (uninitialized) optional.noexcept
, variadic templates, perfect forwarding, static initialization.It sometimes happens that a function that is declared to return values of type T
may not have a value to return. For one instance, consider function double sqrt(double)
. It is not defined for negative numbers. The only way function sqrt can find itself in the situation where it cannot produce a value is when it is passed an invalid argument, and it is possible for the caller to check if the argument is valid. Therefore, such cases are dealt with by stating a function precondition. Violating the precondition may either result in undefined behavior, or (as it is the case for std::vector::at
) may be defined to throw an exception. However, there are cases where we cannot know whether a function is able to return a value before we call it. For instance:
char c = stream.getNextChar(); int x = DB.execute("select x_coord from coordinates where point_id = 112209");
In the first case, one could argue that stream
could provide another function for checking if the end of stream has been reached. But for the latter there is no easy way to make sure that the requested information exists in the database before we request for it. Also, throwing an exception is not a good solution, because there is nothing unusual or erroneous about not having found a record in the DB.
Sometimes it is useful to indicate that we are unable or do not want to provide one of the function arguments:
void execute( function<void(int)> fa, function<void(int)> fb ) { int i = computeI(); fa(i); // implicit assumption that fa != nullptr if (fb) { fb(i); } }
Here, fb
is an optional argument, and it typically requires an if-statement in function body. It is often argued that such design can be replaced by providing two function overloads, however this also is problematic: it adds certain duplication; may make the code less clear; the number of overloads increases expotentially with the number of optional parameters.
Some types are capable of storing a special null-state or null-value. It indicates that no 'meaningful' value has been assigned to the object yet. It is then possible to query the object whether it contains a null-state, typically by invoking a contextual conversion to type bool
or by checking for equality with nullptr
. Examples of such types include: std::unique_ptr
or std::function
. This is convenient for instance when implementing a lazy initialization
optimization:
class Car { mutable unique_ptr<const Engine> engine_; public: const Engine& engine() const { if (engine_ == nullptr) { engine_.reset( new engine{engineParams()} ); } return *engine_; } };
Other types, on the other hand, do not provide this capability. For instance, type int
does not have a special value that would signal the null-state. Any value of int
is a valid value. The same goes for user defined types: e.g., Rational<int>
that implements a rational number by holding two int
’s representing a numerator and a denumerator.
For a similar example, consider this function for finding biggest int
.
int find_biggest( const vector<int>& vec ) { int biggest; // = what initial value?? for (int val : vec) { if (biggest < val) { biggest = val; } } return biggest; }
What initial value should we assign to biggest
? Not 0, because the vector may hold negative values. We can use std::numeric_limits<int>::min
. But what if we want to make our function generic? std::numeric_limits
will not be specialized for any possible type. And what if the vector contains no elements? Shall we return minimum possible value? But how will the caller know if the size of the vector was zero, or if it was one with the minimum possible value?
Consider that you have to run three actions in the fixed order:
void runAction1( Resource1 & ); void runAction2( Resource1 &, Resource2 & ); void runAction3( Resource2 & );
Of course, the two resources need to be acquired before using them and released once we are done. This is how we would write it conceptually, if we could assume that none of the operations ever fails or throws exceptions:
Result run3Actions( Parameter param ) // BAD!! { Resource1 res1; Resource2 res2; res1.acquire(param); // res1 scope runAction1( res1 ); // res2.acquire(param); // // res2 scope runAction2( res1, res2 ); // // res1.release(); // // runAction3( res2 ); // res2.release(); // }
Note that the scopes of the two resources overlap. we cannot clearly divide our function into nested scopes that correspond to lifetimes of the resources. This example represents a real-life situation if you imagine that runAction2 is a critical operation, and runAction3 (and perhaps runAction1) is logging, which we can even skip if it fails.
Of course, this code is unacceptable, because it does not take into account that acquire operations, and the three actions may fail. So, we want to rewrite run3Actions using RAII idiom. Especially, that the library author that provides the interface to the two resources also knows that RAII is probably always what we want and the only interface he provides are scope guards:
Result run3Actions( Parameter param ) // selfish { Resource1Guard res1{param}; Resource2Guard res2{param}; runAction1( res1 ); runAction2( res1, res2 ); runAction3( res2 ); }
This solution is somewhat elegant: you first acquire all resources that you will need, and once you are sure you have them all, you just run the actions. But it has one problem. Someone else will also need to use resources we are acquiring. If they need it at the moment, but we own the resource right now, they will be locked, or thrown a refusal exception — they will be disturbed and delayed. Using a resource is a critical part of the program, and we should be only acquiring them for as short a period as possible, for the sake of efficiency: not only our program's but of the entire operating system. In our example above, we hold the ownership of res2 while executing runAction1, which does not require the resource. Similarly, we unnecessarily hold res1 when calling runAction3.
So, how about this?
Result run3Actions( Parameter param ) // slow and risky { { Resource1Guard res1{param}; runAction1( res1 ); } { Resource1Guard res1{param}; Resource2Guard res2{param}; runAction2( res1, res2 ); } { Resource2Guard res2{param}; runAction3( res2 ); } }
It does not have the above-mentioned problem, but it introduces a different one. Now we have to acquire the same resource two times in a row for two subsequent actions. Resource acquisition is critical, may lock us, may slow us down, may fail; calling it four times rather than two is wrong, especially that acquiring the same resource twice may give us different resource properties in each acquisition, and it may not work for our actions.
Not all types provide a cheap default construction, even if they are small in size. If we want to put such types in certain containers, we are risking paying the price of expensive default construction even if we want to assign a different value a second later.
ExpensiveCtor array[100]; // 100 default constructions std::array<ExpensiveCtor, 100> arr; // 100 default constructions std::vector<ExpensiveCtor> vec(100); // 100 default constructions
The above mentioned problems are usually dealt with in C++ in three ways:
EOF
, -1, 0, numeric_limits<T>::min
.pair<T, bool>
.Technique (1) suffers from the lack of uniformity. Special value, like EOF
is not something characteristic of the type (int
), but of the particular function. Other function may need to use a different special value. The notable example is the standard function atoi
, where 0 may indicate either an unsuccessful conversion, or a successful conversion to value 0. And again, sometimes it is not even possible to designate a value with a special meaning, because all values of a given type are equally likely to appear; for instance:
bool accepted = DB.execute("select accepted from invitations where invitation_id = 132208");
Technique (2) is problematic because it requires both members of pair
to be initialized. But one of the reasons we are not returning a 'normal' value from a function or do not want to initialize the object just yet, is because we did not know how to initialize it. In case of optional int
we could give it a rubbish value or leave it uninitialized, but user defined types, including resources, may not provide a default constructor, and require some effort to perform initialization.
Technique (3) is general. It uses value nullptr
to indicate the special value. Users can unequivocally test if the value is indeed absent and being formally undefined behavior to access an object pointed to by a null pointer. It also does not require initializing the object unnecessarily. But it comes with different problems. Automatic objects created inside functions cannot be returned by pointer. Thus it often requires creating objects in free store which may be more expensive than the expensive initialization itself. It also requires manual memory management problems. The latter problem can be dealt with by using std::unique_ptr
, but this is still a pointer, and we must abandon value semantics. Now we return a smart pointer: we have shallow copy and shallow comparison.
optional
The utility presented here is not a smart pointer. Even though it provides operators ->
and *
, it has full value semantics: deep copy construction, deep copy assignmet, deep equality and less-than comparison, and constness propagation (from optional object to the contained value).
Conceptually, optional
can be illustrated by the following structure.
template <typename T> struct optional { bool is_initialized_; typename aligned_storage<sizeof(T), alignof(T)>::type storage_; };
Flag is_initialized_
stores the information if optional
has been assigned a value of type T
. storage_
is a raw fragment of memory (allocated within optional
object) capable of storing an object of type T
. Objects in this storage are created and destroyed using placement new
and pseudo destructor call as member functions of optional
are executed and based on the value of flag is_initialized_
.
Alternatively, one can think of optional<T>
as pair<bool, T>
with one important difference: if first
is false
, member second
has never been even initialized, even with default constructor or value-initialization.
Default construction of optional<T>
creates an an object that stores no value of type T
. No default constructor of T
is called. T
doesn't even need to be DefaultConstructible
. We say that thus created optional object is disengaged. We need the pair of artificial names, 'engaged' and 'disengaged', in order not to overload the regular meaning of terms 'initialized' and 'uninitialized'. The optional object is initialized (the lifetime of optional<T>
has started), but it is disengaged (the lifetime of the contained object has not yet started). Trying to access the value of T
in this state causes undefined behavior. The only thing we can do with a disengaged optional object is to query whether it is engaged, copy it, compare it with another optional<T>
, or engage it.
optional<int> oi; // create disengaged object optional<int> oj = nullopt; // alternative syntax oi = oj; // assign disengaged object optional<int> ok = oj; // ok is disengaged if (oi) assert(false); // 'if oi is engaged...' if (!oi) assert(true); // 'if oi is disengaged...' if (oi != nullopt) assert(false); // 'if oi is engaged...' if (oi == nullopt) assert(true); // 'if oi is disengaged...' assert(oi == ok); // two disengaged optionals compare equal
We can create engaged optional objects or engage existing optional objects by using converting constructor (from type T
) or by assigning a value of type T
.
optional<int> ol{1}; // ol is engaged; its contained value is 1 ok = 2; // ok becomes engaged; its contained value is 2 oj = ol; // oj becomes engaged; its contained value is 1 assert(oi != ol); // disengaged != engaged assert(ok != ol); // different contained values assert(oj == ol); // same contained value assert(oi < ol); // disengaged < engaged assert(ol < ok); // less by contained value
We access the contained value using the indirection operator.
int i = *ol; // i obtains the value contained in ol assert(i == 1); *ol = 9; // the object contained in ol becomes 9 assert(*ol == 9);
We also provide consistent operator->
. The typical usage of optional
requires an if-statement.
if (ol) process(*ol); // use contained value if present else processNil(); // proceed without contained value
If the action to be taken for disengaged optional
is to proceed with the default value, we provide a convenient idiom:
process(get_value_or(ol, 0)); // use 0 if ol is disengaged
Sometimes the initialization from T
may not do. If we want to skip the copy/move construction for T
because it is too expensive or simply not available, we can call an 'emplacing' constructor, or function emplace
.
optional<Guard> oga; // Guard is non-copyable (and non-moveable) optional<Guard> ogb(emplace, "res1"); // initialzes the contained value with "res1" optional<Guard> ogc(emplace); // default-constructs the contained value oga.emplace("res1"); // initialzes the contained value with "res1" oga.emplace(); // destroys the contained value and // default-constructs the new one
There are two ways to disengage a perhaps engaged optional object:
ok = nullopt; // if ok was engaged calls T's dtor oj = {}; // assigns a temporary disengaged optional oga = nullopt; // OK: disengage the optional Guard ogb = {}; // ERROR: Guard is not Moveable
Optional propagates constness to its contained value:
const optional<int> c = 4; int i = *c; // i becomes 4 *c = i; // ERROR: cannot assign to const int&
It is also possible to create optional lvalue references, although their interface is limited.
int i = 1; int j = 2; optional<int&> ora; // disengaged optional reference to int optional<int&> orb = i; // contained reference refers to object i *orb = 3; // i becomes 3 ora = j; // ERROR: optional refs do not have assignment from T ora = {j}; // ERROR: optional refs do not have copy/move assignment ora = orb; // ERROR: no copy/move assignment ora.emplace(j); // OK: contained reference refers to object j ora.emplace(i); // OK: contained reference now refers to object i ora = nullopt; // OK: ora becomes disengaged
Since optional lvalue references are rebindable, may be disengaged, and do not have special powers (such as extending the life-time of a temporary), they are very similar to pointers, except that they do not provide pointer arithmetic. Optional rvalue references are not allowed.
Type optional<T>
is a wrapper over T
, thus its exception safety guarantees depend on exception safety guarantees of T
. We expect (as is the case for the entire C++ Standard Library) that destructor of T
does not throw exceptions. Copy assignment of optional<T>
provides the same exception guarantee as copy assignment of T
and copy constructor of T
(i.e., the weakest of the two). Move assignment of optional<T>
provides the same exception guarantee as move assignment of T
and move constructor of T
. Member function emplace
provides basic guarantee: if exception is thrown, optional<T>
becomes disengaged, regardless of its prior state. No operation on optional references throws exceptions.
With optional<T>
problems described in Motivation section can be solved as follows. For lazy initialization:
class Car { mutable optional<const Engine> engine_; mutable optional<const int> mileage_ public: const Engine& engine() const { if (engine_ == nullopt) engine_.emplace( engineParams() ); return *engine_; } const int& mileage() const { if (!mileage_) mileage_ = initMileage(); return *mileage_; } };
The algorithm for finding the greatest element in vector can be written as:
optional<int> find_biggest( const vector<int>& vec ) { optional<int> biggest; // initialized to not-an-int for (int val : vec) { if (!biggest || *biggest < val) { biggest = val; // or: biggest.emplace(val); } } return biggest; }
Or, if the caller may wish to modify the smallest element:
optional<int&> find_biggest( vector<int>& vec ) { optional<int&> biggest; for (int & val : vec) { if (!biggest || *biggest < val) { biggest.emplace(val); } } return biggest; }
Missing return values are naturally modelled by optional values:
optional<char> c = stream.getNextChar(); optional<int> x = DB.execute("select ..."); storeChar( get_value_or(c, '\0') ); storeCount( get_value_or(x, -1) );
Optional arguments can be implemented as follows:
template <typename T> T getValue( optional<T> newVal = nullopt, optional<T&> storeHere = nullopt ) { if (newVal) { cached = *newVal; if (storeHere) { *storeHere = *newVal; // LEGAL: assigning T to T } } return cached; }
Manually controlling the life-time of guard-like objects can be achieved by emplacement operations and nullopt
assignment:
{ optional<Guard> grd1{emplace, "res1", 1}; // guard 1 initialized optional<Guard> grd2; grd2.emplace("res2", 2); // guard 2 initialized grd1 = nullopt; // guard 1 released } // guard 2 released (in dtor)
It is possible to use tuple
and optional
to emulate multiple return valuse for types without default constructor:
tuple<Date, Date, Date> getStartMidEnd(); void run(Date const&, Date const&, Date const&); // ... optional<Date> start, mid, end; // Date doesn't have default ctor (no good default date) tie(start, mid, end) = getStartMidEnd(); run(*start, *mid, *end);
value_ptr
N3339[7] proposes a smart pointer template value_ptr
. In short, it is a smart pointer with deep copy semantics. It has a couple of features in common with optional
: both contain the notion of optionality, both are deep-copyable. Below we list the most important differences.
value_ptr
requires that the pointed-to object is allocated in the free store. This means that the sizeof(value_ptr<T>)
is fixed irrespective of T
. value_ptr
is 'polymorphic': object of type value_ptr<T>
can point to an object of type DT
, derived from T
. The deep copy preserves the dynamic type. optional
requires no free store allocation: its creation is more efficient; it is not "polymorphic".
Relational operations on value_ptr
are shallow: only addresses are compared. Relational operations on optional
are deep, based on object's value. In general, optional
has a well defined value: being disengaged and the value of contained value (if it exists); this value is expressed in the semantics of equality operator. This makes optional
a full value-semantic type. Comparison of value_ptr
does not have this property: copy semantics are incompatible with equality comparison semantics: a copy-constructed value_ptr
does not compare equal to the original. value_ptr
is not a value semantic type.
Nearly every function in the interface of optional
has risen some controversies. Different people have different expectations and different concerns and it is not possible to satisfy all conflicting requirements. Yet, we believe that optional
is so universally useful, that it is worth standardizing it even at the expense of introducing a contorversial interface. The current proposal reflects our arbitrary choice of balance between unambiguousity, genericity and flexibility of the interface. The interface is based on Fernanndo Cacciola's Boost.Optional library,[2] and the users' feedback. The library has been widely accepted, used and even occasionally recommended ever since.
optional<T>
Optional objects serve a number of purposes and a couple of conceptual models can be provided to answer the question what optional<T>
really is and what interface it should provide. The three most common models are:
T
with deferred initialization (and additional interface to check if the object has already been initialized).nullopt_t
and T
.T
's with the maximum size of 1.While (1) was the first motivation for optional
, we do not choose to apply this model, because type optional<T>
would not be a value semantic type: it would not model concept Regular
(if C++ had concepts). In particular, it would be not clear whather being engaged or disengaged is part of the object's state. Programmers who wish to adapt this view, and don't mind the mentioned difficulties, can still use optional
this way:
optional<int> oi; initializeSomehow(oi); int i = (*oi); use(*oi); (*oi) = 2; cout << (*oi);
Note that this usage does not even require to check for engaged state, if one is sure it has been performed. One just needs to use indirection operator consistently anywhere one means to use the initialized value.
Model (2) treats optional<T>
as etier a value of type T
or value nullopt
, allocated in the same storage, along with the way of determining which of the two it is. The interface in this model requires operations such as comparison to T
, comparison to nullopt
, assignment and creation from either. It is easy to determine what the value of the optional object is in this model: the type it stores (T
or nullopt_t
) and possibly the value of T
. This is the model that we propose.
Model (3) treats optional<T>
as a special case container. This begs for a container-like interface: empty
to check if the object is disengaged, emplace
to engage the object, and clear
to disengage it. Also, the value of optional object in this model is well defined: the size of the container (0 or 1) and the value of the element if the size is 1. This model would serve our pupose equally well. The choice between models (2) and (3) is to a certain degree arbitrary. One argument in favour of (2) is that it has been used in practise for a while in Boost.Optional.
optional<T>
In cases T
is a value semantic type capable of storing n distinct values, optional<T>
can be seen as an extended T
capable of storing n + 1 values: these that T
stores and nullopt
. Any valid initialization scheme must provide a way to put an optional objects to any of these states. In addition, some T
s (like scope guards) are not MoveConstructible
and their optional variants still should constructible with any set of arguments that work for T
. Two models have been identified as feasible.
The first requires that you initialize either by providing an already constructed T
on the tag nullopt
.
string s{"STR"}; optional<string> os{s}; // requires Copyable<T> optional<string> ot = s; // requires Copyable<T> optional<string> ou{"STR"}; // requires Movable<T> optional<string> ov = string{"STR"}; // requires Movable<T> optional<string> ow; // disengaged optional<string> ox{}; // disengaged optional<string> oy = {}; // disengaged optional<string> oz = optional<string>{}; // disengaged optional<string> op{nullopt}; // disengaged optional<string> oq = {nullopt}; // disengaged
In order to avoid calling move/copy constructor of T
, we use a 'tagged' placement constructor:
optional<Guard> og; // disengaged optional<Guard> oh{}; // disengaged optional<Guard> oi{emplace}; // calls Guard{} in place optional<Guard> oj{emplace, "arg"}; // calls Guard{"arg"} in place
The in-place constructor is not strictly necessary. It could be dropped because one can always achieve the same effect with a two-liner:
optional<Guard> oj; // start disengaged oj.emplace("arg"); // now engage
Notably, there are two ways to create a disengaged optional object: either by using the default constructor or by calling the 'tagged constructor' that takes nullopt
. One of these could be safely removed and optional<T>
could still be initialized to any state.
An alternative and also comprehensive initialization scheme is to have a variadic perfect forwarding constructor that just forwards any set of arguments to the constructor of the contained object of type T
:
// not proposed optional<string> os{"STR"}; // calls string{"STR"} in place optional<string> ot{2, 'a'}; // calls string{2, 'a'} in place optional<string> ou{}; // calls string{} in place optional<string> or; // calls string{} in place optional<Guard> og; // calls Guard{} in place optional<Guard> oh{}; // calls Guard{} in place optional<Guard> ok{"arg"}; // calls Guard{"arg"} in place optional<vector<int>> ov; // creates 0-element vector optional<vector<int>> ow{}; // creates 0-element vector optional<vector<int>> ox{5, 6}; // creates 5-element vector optional<vector<int>> oy{{5, 6}}; // creates 2-element vector
In order to create a disengaged optional object a special tag needs to be used: either nullopt
or T
-based:
optional<int> oi = nullopt; // disengaged optional<int> oj = optional<int>::nullopt; // disengaged
The latter, perfect forwarding variant, has an obvious advantage: whatever you can initialize T
with, you can also use it to initialize optional<T>
with the same semantics. It becomes even ore useful in copy-initialization contextx like returning values from functions or passing arguments to functions:
void putch(optional<char> oc); putch('c'); putch({}); // char '\0' putch(nullopt); // no char
However, there are also certain problems with this model. First, there are exceptions to perfect forwarding: the tag nullopt
is not forwarded. Also, arguments of type optional<T>
are not. This becomes visible if T
has such constructor:
struct MyType { MyType(optional<MyType>, int = 0); // ... };
Also, in general, it is impossible to perfect-forward initializer_list
as the special deduction rules are involved. Second problem is that optional
's default constructor creates an engaged object and therby triggers the value-initialization of T
. It can be argued that this is only a psychological argument resulting from the fact that other std
components behave this way: containers, smart pointers, function
, and only because perfect forwarding was not available at the time they were designed. However we anticipate that this expectation (valid or not) could cause bugs in programs. Consider the following example:
optional<char> readChar(Stream str) { optional<char> ans; if (str.buffered()) { ans = str.readBuffered(); clearBuffer(); } else if (!str.end()) { ans = str.readChar(); } return ans; }
This is so natural to expect that ans
is not engaged until we decide how we wan to engage it, that people will write this code. And in the effect, if they cannod read the character, they will return an engaged optional object with value '\0'
. For these reasons we choose to propose the former model.
This proposal provides a default constructor for optional<T>
that creates a disengaged optional. We find this feature convenient for a couple of reasons. First, it is because this behaviour is intuitive as shown in the above example of function readChar
. It avoids a certain kind of bugs. Also it satisfies other expectations. If I declare optional<T>
as a non-static member, without any initializer, I may expect it is already initialized to the most natural, disengaged, state regardless of whether T
is DefaultConstructible
or not. Also when declaring a global object, one could expect that default constructor would be initialized during static-initialization (this proposal guarantees that). One could argue that the tagged constructor could be used for that puropse:
int global = nullopt; struct X { optional<M> m = nullopt; };
However, sometimes not providing the tag may be the result of an inadvertent omission rather than concious decision. Because of our default constructor semantics we have to reject the initialization scheme that yses a perfect forwarding constructor. Even if this is fine, one could argue that we do not need a default constructor if we have a tagged constructor. We find this redundancy convenient. For instance, how do you resize a vector<optional<T>>
if you do not have the default constructor? You could type:
vec.resize(size, nullopt);
However, that causes first the creation od disengaged optional, and then copying it multiple times. The use of copy constructor may incur run-time overhead and not be available for non-copyable T
s. Also, it would be not possible to use subscript operator in maps that hold opitonal objects.
Also, owing to this constructor, optional
has a nice side-effect feature: it can make "almost Regular
" types fully Regular
if the lack od default constructor is the only thing they are missing. For instance consider type Date
for representing calendar days: it is copyable movable, comparable, but is not DefaultConstructible
because there is no meaningful default date. However, optional<Date>
is Regular
with a meaningful not-a-date state created by default.
T
)An object of type T
is convertible to an engaged opbject of type optional<T>
:
optional<int> oi = 1; // works
This convenience feature is not strictly necessary because you can achieve the same effect by using tagged forwarding constructor:
optional<int> oi{emplace, 1};
If the latter appears too inconvenient, one can always use funciotn make_optional
described below:
optional<int> oi = make_optional(1); auto oj = make_optional(1);
If the above still appears inconvenient, one could argue that optional
's constructor from T
could still be provided but made explicit. We decided to enable implicit conversion, because it is in accord with the view of optional as an extended type T
capable of storing all 'normal' values of T
+ one additional value: nullopt
this is reflected in object construction and assignment:
optional<unsigned> oi = 1; optional<unsigned> oj = 0; optional<unsigned> ok = nullopt; oi = nullopt; oj = 0; ok = 1;
For the same reason, also construction from nullopt
is non-explicit. Although, in this picture name 'none' for the tag (rather than 'nullopt') would better serve the purpose. In contrast, accessor functions (including comparison operators) do not expose such symmetric interface. Such implicit conversions impose some risk of introducing bugs, and in fact in order to avoid one such possible bug we had to 'poison' comparisons between optional<T>
and T
. (This is explained in detail in section on relational operators.)
bool
for checking engaged stateObjections have been risen to this decision. When using optional<bool>
, contextual conversion to bool
(used for checking the engaged state) might be confused with accessing the stored value. while such mistake is possible, it is not precedent in the standard: types bool*
, unique_ptr<bool>
, shared_ptr<bool>
suffer from the same potential problem, and it was never considered a show-stopper. Some have suggested that a special case in the interface should be made for optional<bool>
specialization. This was however rejected because it would break the generic use of optional
.
Some have also suggested that a member function like is_initialized
would more clearly indicate the intent than explicit conversion to bool
. However, we believe that the latter is a well established idiom in C++ comunity as well as in the C++ Standard Library, and optional
appears so fundamental a type that a short and familiar notation appears more appropriate. It also allows us to combine the construction and checking for being engaged in a condition:
if (optional<char> ch = readNextChar()) { // ... }
nullopt
for indicating disengaged stateThe proposed interface uses special tag nullopt
to indicate disengaged optional
state. It is used for construction, assignment and relational operations. This might rise a couple of objections. First, it introduces redundancy into the interface:
optional<int> opt1 = nullopt; optional<int> opt2 = {}; opt1 = nullopt; opt2 = {}; if (opt1 == nullopt) ... if (!opt2) ... if (opt2 == optional<int>{}) ...
On the other hand, there are usages where the usage of nullopt
cannot be replaced with any other convenient notation:
void run(complex<double> v); void run(optional<string> v); run(nullopt); // pick the second overload run({}); // ambiguous if (opt1 == nullopt) ... // fine if (opt2 == {}) ... // ilegal
While some situations would work with {}
syntax, using nullopt
makes the programmer's intention more clear. Compare these:
optional<vector<int>> get1() { return {}; } optional<vector<int>> get2() { return nullopt; } optional<vector<int>> get3() { return optional<vector<int>>{}; }
The usage of nullopt
is also a consequence of the adapted model for optional: a discriminated union of T
and nullopt_t
. Also, a similar redundancy in the interface already exists in a number of components in the standard library: unique_ptr
, shared_ptr
, function
(which use literal nullptr
for the same purpose); in fact, type requirements NullablePointer
require of types this redundancy.
Name "nullopt" has been chosen because it clearly indicates that we are interested in creating a null (disengaged) optional<T>
(of unspecified type T
). Other short names like "null", "naught", "nothing" or "none" (used in Boost.Optional library) were rejected because they were too generic: they did not indicate unambiguously that it was optional<T>
that we intend to create. Such a generic tag nothing
could be useful in many places (e.g., in types like variant<nothing_t, T, U>
), but is outside the scope of this proposal.
Note also that the definition of tag struct nullopt
is more complicated than that of other, similar, tags: it has explicitly deleted default constructor. This is in order to enable the reset idiom (opt2 = {};
), which would otherwise not work because of ambiguuity when deducing the right-hand side argument.
nullptr
One could argue that since we have keyword nullptr
, which already indicates a 'null-state' for a number of Standard Library types, not necessarily pointers (class template function
), it could be equally well used for optional
. In fact, the previous revision of this proposal did propose nullptr
, however there are certain difficulties that arise when the null-pointer literal is used.
First, the interface of optional
is already criticized for resembling too much the interface of a (raw or smart) pointer, which incorrectly suggests external heap storage and shallow copy and comparison semantics. The "ptr" in "nullptr" would only increase this confusion. While std::function
is not a pointer either, it also does not provide a confusing operator->
, or equality comparison, and in case it stores a function pointer it does shallow copying.
Second, using literal nullptr
in optional
would make it impossible to provide some of the natural and expected initialization and assignment semantics for types that themselves are nullable:
optional<int*>
, optional<const char*>
, optional<M C::*>
, optional<function<void(int)>>
, optional<NullableInteger>
,optional<nullptr_t>
.Should the following initialization render an engaged or a disengaged optional?
optional<int*> op = nullptr;
One could argue that if we want to initialize an engaged optional we should indicate that explicitly:
optional<int*> op{emplace, nullptr};
But this argument would not work in general. One of the goals of the design of optional
is to allow a seamless "optionalization" of function arguments. That is, given the folowing function signature:
void fun(T v) { process(v); }
It should be possible to change the signature and the implementation to:
void fun(optional<T> v) { if (v) process(*v); else doSthElse(); }
and expect that all the places that call function fun
are not affected. But if T
happens to be int*
and we occasionally pass value nullptr
to it, we will silently change the intended behavior of the refactoring: because it will not be the pointer that we null-initialize anymore but a disengaged optional.
Note that this still does not save us from the above problem with refactoring function fun
in case where T
happens to be optional<U>
, but we definately limit the amount of surprises.
In order to avoid similar problems with tag nullopt
, instantiating template optional
with types nullopt_t
and emplace_t
is prohibitted.
There exist, on the other hand, downsides of introducing a special token in place of nullptr
. The number of ways to indicate the 'null-state' for different library components will grow: you will have NULL
, nullptr
, nullopt
. New C++ programmers will ask "which of these should I use now?" What guidelines should be provided? Use only nullptr
for pointers? But does it mean that we should use nullopt
for std::function
? Having only one way of denoting null-state, would make the things easier, even if "ptr" suggests a pointer.
T
? It has been suggested that instead of 'typeless' nullopt
a tag nested in class optional
be used instead:
optional<int> oi = optional<int>::nullopt;
This has several advanages. Namespace std
is not polluted with an additional optional
-specific name. Also, it resolves certain ambiguities when types like optional<
are involved:optional<T>
>
optional<optional<int>> ooi = optional<int>::nullopt; // engaged optional<optional<int>> ooj = optional<optional<int>>::nullopt; // disengaged
void fun(optional<string>); void fun(optional<int>); fun(optional<string>::nullopt); // unambiguous: a typeless nullopt would not do
Yet, we choose to propose a typeless tag because we consider the above problems rare and a typeless tag offers a very short notation in other cases:
optional<string> fun() { optional<int> oi = nullopt; // no ambiguity oi = nullopt; // no ambiguity // ... return nullopt; // no ambiguity }
If the typeless tag does not work for you, you can always use the following construct, although at the expense of invoking a (possibly elided) move constructor:
optional<optional<int>> ooi = optional<int>{}; // engaged optional<optional<int>> ooj = optional<optional<int>>{}; // disengaged
void fun(optional<string>); void fun(optional<int>); fun(optional<string>{}); // unambiguous
It was chosen to use indirection operator because, along with explicit conversion to bool
, it is a very common pattern for accessing a value that might not be there:
if (p) use(*p);
This pattern is used for all sort of pointers (smart or dumb), and it clearly indicates the fact that the value may be missing and that we return a reference rather than a value. The indirection operator has risen some objections because it may incorrectly imply that optional
is a (possibly smart) pointer, and thus provides shallow copy and comparison semantics. We believe that the cost of potential confusion is overweighed by the benefit of an easy to grasp and intuitive interface for accessing the contained value.
We do not think that providing an implicit conversion to T
would be a good choice. First, it would require different way of checking for the epty state; and second, such implicit conversion is not perfect and still requires other means of accessing the contained value if we want to call a member function on it.
One of the design goals of optional
is that objects of type optional<T>
should be valid elements in STL containers and usable with STL algorithms (at least if objects of type T
are). Equality comparison is essential for optional<T>
to model concept Regular
. C++ does not have concepts, but being regular is still essential for the type to be effectively used with STL. Ordering is essential if we want to store optional values in associative containers. A number of ways of including the disengaged state in comparisons have been suggested. The ones proposed, have been crafted such that the axioms of equivalence and strict weak ordering are preserved: disengaged optional<T>
is simply treated as an additional and unique value of T
equal only to itself; this value is always compared as less than any value of T
:
assert (optional<unsigned>{} < optional<unsigned>{0}); assert (optional<unsigned>{0} < optional<unsigned>{1}); assert (!(optional<unsigned>{} < optional<unsigned>{}) ); assert (!(optional<unsigned>{1} < optional<unsigned>{1})); assert (optional<unsigned>{} != optional<unsigned>{0}); assert (optional<unsigned>{0} != optional<unsigned>{1}); assert (optional<unsigned>{} == optional<unsigned>{} ); assert (optional<unsigned>{0} == optional<unsigned>{0});
One could also expect comparisons between T
and optional<T>
. The natural semantics of such comparison would be:
template <class T> bool operator==(const optional<T>& a, const T& b) { return a == make_optional(b); }
We do not propose it because there is no strong motivation for such comparisons. On the contrary, the inadvertent invocation o such comparisons might be disastrous. Consider the following scenario. We have a class that stores the number of passengers:
class MyPlan { unsigned passengerCount; // ... };
At some point we realize that sometimes we will not know the number of passengers: either because we use lazy initialization techniques or because we failed to compute the number. We change the type of the variable:
class MyPlan { optional<unsigned> passengerCount; // ... };
And we might expect that compiler will warn us in every place where we try to access the value of passengerCount
. However the following comparison will continue to compile although the run-time behaviour will be different than the one expected:
bool MyPlan::exceedsCapacity() const { return passengerCount > availableSeats; // availableSeats is of type unsigned int }
Since disengaged optional never compares greater than anything, the effect we have is that if we do not know how many passengers there are we report with certainty that their number does not exceed the capacity. For this reason comparison between optional<T>
and T
are required to be reported as errors at compile-time
This proposal offers three ways of assigning a new contained value to an optional object:
optional<int> o; o = make_optional(1); // copy/move assignment o = 1; // assignment from T o.emplace(1); // emplacement
The first form of assignment is required to make optional
a regular object, useable in STL. We need the second form in order to reflect the fact that optional<T>
is a wrapper for T
and hence it should behave as T
as much as possible. Also, when optional<T>
is viewed as T
with one additional value, we want the values of T
to be directly assignable to optional<T>
. In addition, we need the second form to allow the interoperability with function std::tie
as shown above. The two forms differ only by syntax. Their semantics are practically the same: if o
is disengaged, call T
's copy/move constructor to initialize the contained value; otherwise use T
's copy/move assignment to modify the contained value (here, we skip the cases where the right-hand side optional object is disengaged). The third option, using function emplace
is different in semantics, which is: destroy the contained value (if engaged) and create anew. It does not require that the contained value is even a moveable type, and guarantees no copying/moving.
emplace
This proposal provides an 'in-place' constructor that forwards (perfectly) the arguments provided to optional
's constructor into the constructor of T
. In order to trigger this constructor one has to use the tag struct emplace
. We need the extra tag to disambiguate certain situations, like calling optional
's default constructor and requesting T
's default construction:
optional<Big> ob{emplace, "1"}; // calls Big{"1"} in place (no moving) optional<Big> oc{emplace}; // calls Big{} in place (no moving) optional<Big> od{}; // creates a disengaged optional
The name, suggested by Alberto Ganesh Barbati, is consistent with member functions of containers (and optional
itself), which also indicate similar purpose. On the other hand, it may appear uncomfortable that emplace
becomes overloaded in std
: it is now a member funciton in many container type as well as a tag. If this is considered a serious issue, the tag could be renamed to in_place
.
T
Class template optional
imposes little requirements on T
: it has to be either an lvalue reference type, or a complete object type satysfying the requirements of Destructible
. It is the particular operations on optional<T>
that impose requirements on T
: optional<T>
's move constructor requires that T
is MoveConstructible
, optional<T>
's copy constructor requires that T
is CopyConstructible
, and so on. This is because optional<T>
is a wrapper for T
: it should resemble T
as much as possible. If T
is EqualityComparable
then (and only then) we expect optional<T>
to be EqualityComparable
.
This proposal also contains optional references. These entities are surprising to many people because they do not appear to add any more functionality than pointers do. There exist though a couple of arguments in favour optional references:
optional<T>
can be used in generic code, were T
can be either a reference or an object. nullptr
or not. With optional references the answer to these questions is obvious.In this proposal, optional references provide no assignment from T&
or optional<T&>
. This is because whatever semantics for such assignment is chosen, it is confusing to many programmers. Optional reference can be seen as a reference with postponed initialization. In this case, assignment (to engaged optional reference) should have deep copy semantics: it should assign value to the referred object. On the other hand, an optional reference can be seen as a pointer with different syntax. In this case the assignment (to engaged optional reference) should change the reference, so that it refers to the new object. Neither of these models appears more valid than the other, so we disable assignment to avoid any confusion. In exchange, we provide member function emplace
, which provides the 'pointer with special syntax' semantics. The other semantics can be implemented by using the following idiom:
void assign_norebind(optional<T&>& optref, T& obj) { if (optref) *optref = obj; else optref.emplace(obj); }
The choice not to provide any assignment is based on the observation that any semantics of such assignment is counterintuitive to some people. If allowed, the assignment is likely to cause run-time surprises. We choose to move the surprise from run-time to compile-time.
Some people still expressed disappointment that optional references are not CopyAssignable
, and they would rather have the assignment back regardless of the semantics. If the feedback from the LWG is that optional references should be CopyAssignable
, we consider providing copy and move assignment with reference rebinding semantics (the ones offered by member function emplace
), but still prohibit the direct assignment from a reference:
// backup proposal int i = 0; int j = 1; optional<int&> ori; optional<int&> orj = j; *orj = 2; assert (j == 2); ori = i; // ERROR: no assignment from int& ori = {i}; // OK: assignemnt from optional<int&> orj = ori; // OK: rebinding assignemnt from optional<int&> *orj = 4; assert (j == 2); assert (i == 4);
Optional referencs cannot provide an essential feature of native references: extending the life-time of temporaries (rvalues). Temporaries can be bound to (1) rvalue references and to (2) lvalue references to const. In order to avoid dangling reference problems we need to prevent either type of binfing to optional references. In order to prevent the former, we disallow optional rvalue references altogether. We are not aware of any practical use case for such entities. Since optional lvalue references to const appear useful, we avoid the rvalue binding problem by requiring implementations to "poison" rvalue reference constructors for optional lvalue references to const. This may appear surprising as it is inconsistent with normal (non-optional) reference behavior:
const int& nr = int{1}; // ok optional<const int&> or = int{1}; // error: int&& ctor deleted
First draft of this revision required an aggressive usage of conditional noexcept
specifications for nearly every, member- or non-member-, function in the interface. For instance equality comparison was to be declared as:
template <class T> bool operator==(const optional<T>& lhs, const optional<T>& rhs) noexcept(noexcept(*lhs == *rhs));
This was based on one of our goals: that we want optional<T>
to be applicable wherever T
is applicable in as many situations as reasonably possible. One such situation occurs where no-throw operations of objects of type T
are used to implement a strong exception safety guarantee of some operations. We would like objects of type optional<T>
to be also useable in such cases. However, we do not propose this aggressive conditional no-throw guarantees at this time in order for the proposed library component to adhere to the current Library guidlines for conditional noexcept
: it is currently only used in move constructor, move assignment and swap
. One exception to this rule, we think could be made for optional's move constructor and assignment from type T&&
, however we still do not propose this at this time in order to avoid controversy.
Constructors and mutating functions that disengage an optional object are required to be noexcept(true)
: they only call T
's destructor and impose no precondition on optional object's or contained value's state. The same applies to the observers that check the disengaged/engaged state.
The observers that access the contained value (or address, for optional references), following the guidelines from N3248[6], are declared as noexcept(false)
because they impose a precondition that optional object shall be engaged. These operations are still required not to throw exceptions.
In general, operations on optional objects only throw, when operations delegated to the contained value throw.
Nearly all operations on opeional references are noexcept(true)
. This is because optional reference is almost a pointer (with a different interface), and can be used as a pointer to implement strong exception and therefore the guarantee.
There are two purposes of making functions and especially constructors constexpr
:
This proposal only aims at the first of the two goals. We can imagine use cases where a global optional object is initialized in two phases: first to a disengaged state in static-initialization phase, and second, after the program (function main
) has started, to the engaged state by initializing the contained value with arguments available only at runtime. This also enables constant initialization for other types that contain optional objects.
Making optional<T>
a literal-type in general is impossible: the destructor cannot be trivial because it has to execute an operation that can be conceptually described as:
~optional() { if (is_engaged()) destroy_contained_value(); }
It is still possible to make the destructor trivial for T
's which provide a trivial destructor themselves, and we know an efficient implementation of such optional<T>
with compile-time interface — except for copy constructor and move constructor — is possible. However, since such requirement is very restrictive on implementations, and since we cannot think of any convincing use case for a full compile-time interface, we do not propose it at this time. We believe that if you are able to determine at compile-time whether you need an engaged or disengaged optional<T>
, you probably need T
alone or no value whatsoever.
Making an optional reference a literal type, on the other hand, is possible and fairly easy; but again, we cannot think of a practical use-case for it, so here also we only propose to make constexpr
the initialization to disengaged state.
When a disengaged optional object is moved from (i.e., when it is the source object of move constructor or move assignment) its state does not change. When an engaged object is moved from, we move the contained value, but leave the optional object engaged. A moved-from contained value is still valid (although possibly not specified), so it is fine to consider such optional object engaged. An alternative approach would be to destroy the contained value and make the moved-from optional object disengaged. However, we do not propose this for performance reasons.
In contexts, like returning by value, where you need to call the destructor the second after the move, it does not matter, but in cases where you request the move explicitly and intend to assign a new value in the next step, and if T
does not provide an efficient move, the chosen approach saves an unnecessary destructor and constructor call:
optional<array<Big>> oo = ... // array doesn't have efficient move op = std::move(oo); oo = std::move(tmp);
The fact that the moved-from optional is not disengaged may look "uncomfortable" at first, but this is an invalid epectation. The only thing that can be legitimately expected of a moved from object (optional object, in particular) is that it can be assigned to or destroyed without causing any resource leak or undefined behavior.
The proposed interface for optional values does not contain IO operations: operator<<
and operator>>
. While we believe that they would be a useful addition to the interface of optional objects, we also observe that there are some technical obstacles in providing them, and we choose not to propose them at this time.
One can imagine a couple of ways in which IO-operations for any streamable type T
could be expected to work. The differences are mostly the consequence of different conceptual models of optional types, as well as different use cases that programmers may face. Below we list the possible ways of outputting the value of optional object.
"OPT[v]"
, where v
represents the contained value, if engaged; otherwise output something like "OPT[]"
.The first option is a consequence of the model where optional<T>
is a T
with deferred initialization, but which is still initialized before first usage. This is not the model that we advocate, so this behavior of operator<<
is rejected. However this behavior can be achieved by accessing the contained value of optional object on each usage:
optional<int> oi; initialize(oi); cin >> (*oi); cout << (*oi);
The second option appears useful in certain contexts, where we want optional objects to indicate some supplementary, often missing, information:
struct FlatNumber { unsigned number_; optional<char> letter_; }; ostream& operator<<( ostream& out, FlatNumber n ) { return out << n.number_ << n.letter_; } // outputs "10", "11", "11A", ...
However, in general the results would be ambiguous. Does output "1 0"
indicate two engaged optional<int>
s, or three, one of which (which one?) is disengaged, or 77 optional<int>
s? Or are these perhaps two int
s? Also, It is not possible to implement a consistent operator>>
in this case. It may not be a problem itself, and providing only one operator is not a precedent in the standard (consider std::thread::id
); alternatively, operator>>
could be implemented inconsistently: by simply calling T
's operator>>
.
The third choice appears attractive at first glance, but there is no good representation for the special sequence that would produce no ambiguities. Whatever sequence we choose, it is also a valid representtion of std::string
; thus if we need to interpret the special sequence, say "~~~"
as optional<string>
, we do not know if it is a disengaged object, or engaged one with contained value of "~~~"
. On the other hand, some people have argued that this ambiguity is worth the usefulness of a simple tool for logging.
While the fourth choice presented above still comes with some similar ambiguities, it is posssible to implement a variant thereof that is not ambiguous. Such solution has been implemented in Boost.Tuple library[5]: user has to register a sequence of letters that represent "an opening bracket" of the optional object's contained value, and similarly register an another sequence for representing a "closing bracket." This would be the user's responsibility to make sure that the chosen sequences are unambiguous, if default sequences (e.g., "["
and "]"
) do not suffice. However, this solution is not without certain controversy.
Currently all streamable types in the library have a nice property that string representation that is streamed out or read in is similar to the format of literals in C++ used to initialize variables. Thus, whatever you type into the console that you intend your program to read, could be equally well typed directly in the C++ code as a literal — of course, to certain extent. The text that the program requires of users to read and type is simply nice.
This controversy is charachteristic not only of optional
. Library components like containers, pairs, tuples face the same issue. At present IO operations are not provided for these types. Our preference for optional
is to provide an IO solution compatible with this for containers, pairs and tuples, therefore at tis point we refrain from proposing a solution for optional
alone.
NullableProxy
Along with the developement of this proposal, we observe that certain abstraction is common to optional objects, as well as to raw and smart pointers, and is useful enough to provide type requirements for certain class of algorithms. We call this concept NullableProxy
. Basically the concept indicates that a type is a 'proxy' for another type. The operations allowed are: checking if there exists an object that our proxy can indirect us to and the indirection operation. The operations can be summarized by the following use-case:
temmplate <class NullableProxy> void test(NullableProxy&& np) { if (np) // 'has-object' check auto&& obj = *np; // object access if (!np) {} // 'doesn't have object' }
These requirements are sufficient to specify a couple of algorithms (not proposed), like the one below:
template <typename NullableProxy> // enable_if: decltype(*declval<NullableProxy>()) is EqualityComparable bool equal_pointees( const NullableProxy& x, const NullableProxy& y ) { return bool(x) != bool(y) ? false : ( x ? *x == *y : true ); }
This is exactly the logic for the equality comparison of optional values, and could be used as an implementation of optional<T>::operator==
. A similar algorithm for less-than comparison can be specified. The third example is function get_value_or
discussed below.
Requirements NullableProxy
overlap with requirements NullablePointer
. Their common part could be extracted to separate requirements, say Nullable
, but these requirements are to small to be useful alone for anything.
We do not propose to add NullableProxy
to Library at this time, but we consider it a useful future addition.
get_value_or
This function template returns a value stored by the optional
object if it is engaged, and if not, it falls back to the default value specified in the second argument. This method for specifying default values on the fly rather than tying the default values to the type is based on the observation that different contexts or usages require different default values for the same type. For instance the default value for int
can be 0 or -1. The callee might not know what value the caller considers special, so it returns the lack of the requested value explicitly. The caller may be better suited to make the choice what special value to use.
optional<int> queryDB(std::string); void setPieceCount(int); void setMaxCount(int); setPieceCount( get_value_or(queryDB("select piece_count from ..."), 0) ); setMaxCount( get_value_or(queryDB("select max_count from ..."), numeric_limits<int>::max()) );
The decision to provide this function is controversial itself. As pointed out by Robert Ramey, the goal of the optional
is to make the lack of the value explicit. Its syntax forces two control paths; therefore we will typically see an if
-statement (or similar branching instruction) wherever optional
is used. This is considered an improvement in correctness. On the other hand, using the default value appears to conflict with the above idea. One other argument against providing it is that in many cases you can use a ternary conditional operator instead:
auto&& cnt = queryDB("select piece_count from ..."); setPieceCount(cnt ? *cnt : 0); auto&& max = queryDB("select max_count from ..."); setMaxCount(max ? std::move(*max) : numeric_limits<int>::max());
However, in case optional objects are returned by value and immediately consumed, the ternary operator syntax requires more typing and explicit move
.
We did not make it a member function for two reasons. (1) It can be implemented by using only the public interface of optional
. (2) This function template could be equally well be applied to any type satysfying the requirements of NullableProxy
. In this proposal, function get_value_or
is defined only for optional
s but being a non-member function allows this extension in the future.
The second argument in the function template's signature is not T
but any type convertible to T
:
template <class T, class V> typename decay<T>::type get_value_or(const optional<T>& op, V&& v); template <class T, class V> typename decay<T>::type get_value_or(optional<T>&& op, V&& v);
This allows for a certain run-time optimization. In the following example:
optional<string> op{"cat"}; string ans = get_value_or(op, "dog");
Because the optional object is engaged, we do not need the fallback value and therefore to convert the string literal "dog"
into type string
.
The function also works for optional references. In this case the returned value is created from the referred object; a copy is returned. It has been argued that the function should return by constant reference rather than value, which would avoid copy overhead in certain situations:
void observe(const X& x); optional<X> ox { /* ... */ }; observe( get_value_or(ox, X{args}) ); // unnecessary copy
However, the benefit of the function get_value_or
is only visible when the optional object is provided as a temporary (without the name); otherwise, a ternary operator is equally useful:
optional<X> ox { /* ... */ }; observe(ox ? *ok : X{args}); // no copy
Also, returning by reference would be likely to render a dangling reference, in case the optional object is disengaged, because the second argument is typically a temporary:
optional<X> ox {nullopt}; auto&& x = get_value_or(ox, X{args}); cout << x; // x is dangling!
It has also been suggested (by Luc Danton) that function get_value_or<T, V>
should return type decay<common_type<T, V>::type>::type
rather than decay<T>::type
. This would avoid certain problems, such as loss of accuracy on arithmetic types:
// not proposed std::optional<int> op = /* ... */; long gl = /* ... */; auto lossless = get_value_or(op, gl); // lossless deduced as long rather than int
However, we did not find many practical use cases for this extension, so we do not propose is at this time.
make_optional
We also propose a helper function make_optional
. Its semantics is closer to that of make_pair
or make_tuple
than that of make_shared
. You can use it in order for the type of the optional to be deduced:
int i = 1; auto oi = make_optional(i); // decltype(oi) == optional<int> auto ri = make_optional(ref(i)); // decltype(ri) == optional<int&>
This may occasionally be useful when you need to pick the right overload and not type the type of the optional by hand:
void fun(optional<complex<double>>); void fun(Current); // complex is convertible to Current complex<double> c{0.0, 0.1}; fun(c); // ambiguous fun({c}); // ambiguous fun(make_optional(c)); // picks first overload
This is not very useful in return statements, as long as the converting constructor from T
is implicit, because you can always use the brace syntax:
optional<complex<double>> findC() { complex<double> c{0.0, 0.1}; return {c}; }
make_shared
-like function does not appear to be useful at all: it is no different than manually creating a temporary optional object:
// not proposed fun( make_optional<Rational>(1, 2) ); fun( optional<Rational>{1, 2} ); // same as above
It would also not be a good alternative for tagged placement constructor, because using it would require type T
to be MoveConstructible
:
// not proposed auto og = make_optional<Guard>("arg1"); // ERROR: Guard is not MoveConstructible
Such solution works for shared_ptr
only because its copy constructor is shallow. One useful variant of shared_ptr
-like make_optional
would be a function that either creates an engaged or a disengaged optional based on some boolean condition:
// not proposed return make_optional_if<Rational>(good(i) && not_bad(j), i, j); // same as: if (good(i) && not_bad(j)) { return {i, j}; } else { return nullopt; } // same as: optional<Rational> or = nullopt; if (good(i) && not_bad(j)) or.emplace(i, j); return or; // move-construct on return
Since this use case is rare, and the function call not that elegant, and a two-liner alternative exists, we do not propose it.
At some point the following goal was considered for optional
; it is the property that could informally be called "copy initialization forwarding". It is somewhat similar to the one-argument version of perfect forwarding constructor; i.e., if a given initializer can be used to copy-initialize objects of type T
, it should also be possible to to use it to copy-initialize objects of type optional<T>
with the same samantics as initializing object of type T
. This goal cannot be achieved in 100% without severely compromising other design goals. For instance, we cannot guarantee the following:
T x = {}; // "{}" is the initializer; x is value-initialized optional<T> ox = {}; // same initializer; contained value not initialized assert (x == *ox); // not guaranteed!
Apart from this default initialization case, and a couple of others (cocncerning initializer-list), "copy initialization forwarding" could be provided for optional
.
Since optional<T>
can be thought of as an "almost T
", one could expect that if the following works:
void fun(std::string s); fun("text");
the following should also work:
void gun(optional<std::string> s); gun("text");
However, naively implementing a converting constructor would also enable a non-explicit converting constructor from any type U
to type optional<T>
for any type T
. This would turn some types that are explicitly constructible into optional types that are implicitly constructible. Consider:
void explicit_conv( int * ptr ) { unique_ptr<int> v = ptr; // ILLEGAL } void implicit_conv( int * ptr ) { optional<unique_ptr<int>> v = ptr; // LEGAL }
In order to make the former example work on the one hand and to prevent the problem with the latter example on the other, we considered a solution that could be informally called a conditionally-explicit converting constructor. We could achieve this by specifying two constructor templates with identical template and function parameters, one explicit and one non-explicit, and make them mutually exclusive by means of SFINAE:
template <class U> // enable_if: Constructible<T, U&&> && !Convertible<U&&, T> explicit optional<T>::optional(U&&); template <class U> // enable_if: Convertible<U&&, T> optional<T>::optional(U&&);
Such concept-like behaviour as used above can be implemented in C++ with type traits and enable_if
. It was noted, however, that the existence of such converting constructor would cause unexpected ambiguities in overload resolution. Consider the following scenario. We start from a working program:
// library void fun(string const& s); // usage fun("hello");
At some point we decide to add a second overload that accepts an optional string:
// library void fun(string const& s); void fun(optional<string> const& s); // new overload // usage fun("hello"); // ERROR: ambiguity
Does it make sense to add an overload for optional rather than substituting it for the original? It might be useful for performance reasons: if you already have string
it is cheaper to bind it directly to string const&
than to create a temporary optional object and trigger the copy constructor of string
:
// library void fun(optional<string> const& s); // only this fun // usage string s = "hello"; fun(s); // copy ctor invoked!
This example shows how an implicit conversion can cause an inadvertent and unexpected (potentially expensive) copy constructor. For this reason we do not propose a converting constructor from arbitrary type U
. (Although we do propose a converting constructor from T
.)
initializer_list
Another feature worth considering is a "sequence constructor" (one that takes initializer_list
as its argument). It would be enabled (in enable_if
sense) only for these T
s that themself provide a sequence constructor. This would be usefult to fully support two features we already mentioned above (but chose not to propose).
First, our goal of "copy initialization forwarding" for optional
also needs to address the following usages of initializer_list
:
vector<int> v = {1, 2, 4, 8}; optional<vector<int>> ov = {1, 2, 4, 8}; assert (v == *ov);
This is not only a syntactical convenience. It also avoids subtle bugs. When perfect forwarding constructor is implemented naively with one variadic constructor, optional vector initialization may render surprising result:
optional<vector<int>> ov = {3, 1}; assert (*ov == vector{3, 1}); // FAILS! assert (*ov == vector{1, 1, 1}); // TRUE!
However this sequence constructor feature is incompatible with another one: default constructor creating a disengaged optional. This is because, as outlined in the former example, initializer {}
, that looks like 0-element list, is in fact interpretted as the request for value-initialization (default constructor call). This may hit programmers that use initializer list in "generic" context:
template <class ...A> // enable_if: every A is int void fwd(const A&&... a) { optional<vector<int>> o = {a...}; assert (bool(o)); // not true for empty a }
If this feature were to be added, we would need to provide an assignment from initializer list and variadic 'emplacement' constructor with the first forwarded argument being initializer_list
:
ov = {1, 2, 4, 8}; allocator<int> a; optional<vector<int>> ou { emplace, {1, 2, 4, 8}, a }; assert (ou == ov);
Since we are not proposing neither perfect forwarding constructor, nor the "copy initialization forwarding", we are also not proposing the sequence constructor. However, in this proposal, the following constructs work:
optional<vector<int>> ov{emplace, {3, 1}}; assert (*ov == vector{3, 1}); ov.emplace({3, 1}); assert (*ov == vector{3, 1});
optional<optional<T>>
The necessity to create a "double" optional explicitly does not occur often. Such type may appear though in generic contexts where we create optional<V>
and V
only happens to be optional<T>
. Some special behavior to be observed in this situation is the following. When copy-initializing with nullopt
, the "outermost" optional is initialized to disengaged state. Thus, changing function argument from optional<T>
to optional<optional<T>>
will silently break the code in places where the argument passed to function happens to be of type nullopt_t
:
// before change void fun(optional<T> v) { process(v); } fun(nullopt); // process() called // after change void fun(optional<optional<T>> v) { if (v) process(*v); else doSthElse(); } fun(nullopt); // process() not called!
This issue would not arise if nullopt
were T
-specific:
fun(optional<T>::nullopt); // process() called fun(optional<optional<T>>::nullopt); // process() not called
Since T
-dependent nullopt
is not proposed, in order to creae an engaged optional containing a disengaged optional, one needs to use one of the following constructs:
optional<optional<T>> ot {emplace}; optional<optional<T>> ou {emplace, nullopt}; optional<optional<T>> ov {optional<T>{}};
Also note that make_optional
will create a "double" optional when called with optional argument:
optional<int> oi; auto ooi = make_optional(oi); static_assert( is_same<optional<optional<int>>, decltype(ooi)>::value, "");
It has been suggested, and in fact implemented in Boost.Optional, that optional
shall have an another constructor with the first argument of type bool
. The value of this argument should be used to determine whether the object should be disengaged, or engaged using the remaining arguments. If we wanted to provide it in optional
and disampiguate the situations where the contained value is also initialized with the first argument of type bool
, it could be easily done by providing a yet another tag (similar to emplace_t
):
bool doIt = false; tr2::optional<string> opstr1{ tr2::only_if(doIt), 3, 'x' }; // disengaged doIt = true; tr2::optional<string> opstr2{ tr2::only_if(doIt), 3, 'x' }; // contained value is "xxx"
However, we do not see a practical use case for this usage. Undoubtadly, it spares you from an explicit if-statement and a two-phase initialization of the optional object, but then it appears obvious that at some time you need to check the value of doIt
anyway, because you do not even know the state of the optional object. It is at that time that you may as well decide to initialize the contained value:
optional<string> process( bool doIt ) { fun1(doIt); optional<string> optstr; if (doIt) { // we ned an if to conditionally call fun2() fun2(); optstr.emplace(3, 'x'); } return optstr; }
Also, even if you create optional as disengaged in the conditional constructor, you still have to compute the values of the arguments that you could potentially use to initialize the contained value, so the two-phase initialization may look more attractive.
For these reasons we do not propose such conditional constructor at this point. However, there appears to be no difficulty in adding it if we find convincing use cases.
Add new header in Table 14 (C++ library headers).
Table 14 — C++ library headers <algorithm>
<fstream>
<list>
<ratio>
<tuple>
<array>
<functional>
<locale>
<regex>
<typeindex>
<atomic>
<future>
<map>
<set>
<typeinfo>
<bitset>
<initializer_list>
<memory>
<sstream>
<type_traits>
<chrono>
<iomanip>
<mutex>
<stack>
<unordered_map>
<codecvt>
<ios>
<new>
<stdexcept>
<unordered_set>
<complex>
<iosfwd>
<numeric>
<streambuf>
<utility>
<condition_variable>
<iostream>
<optional>
<string>
<valarray>
<dequeue>
<istream>
<ostream>
<strstream>
<vector>
<exception>
<iterator>
<queue>
<system_error>
<forward_list>
<limits>
<random>
<thread>
After chapter 20.4 Tuples [tuple], insert a new paragraph. (Chapter [template.bitset] (Class template bitset
) becomes 20.6.)
20.5 Optional objects [optional]
20.5.1 In general [optional.general]
This subclause describes class template
optional
that represents optional objects. An optional object for object types is an object that contains the storage for another object and manages the lifetime of this contained object. The contained object may be initialized after the optional object has been initialized, and may be destroyed before the optional object has been destroyed. The initialization state of the contained object is tracked by the optional object. An optional object for lvalue reference types is an object capable of storing the address of another object. The address stored by the optional object can be canged or set to a value that does not represent a valid address.20.5.2 Header <optional> synopsis [optional.synop]
namespace std { namespace experimental { // 20.5.4,optional
for object types template <class T> class optional; // 20.5.5,optional
for lvalue reference types template <class T> class optional<T&>; // 20.5.6, In-place construction struct emplace_t{}; constexpr emplace_t emplace{}; // 20.5.7, Disengaged state indicator struct nullopt_t{see below}; constexpr nullopt_t nullopt(unspecified); // 20.5.8, Relational operators template <class T> bool operator==(const optional<T>&, const optional<T>&); template <class T> bool operator!=(const optional<T>&, const optional<T>&); template <class T> bool operator<(const optional<T>&, const optional<T>&); template <class T> bool operator>(const optional<T>&, const optional<T>&); template <class T> bool operator<=(const optional<T>&, const optional<T>&); template <class T> bool operator>=(const optional<T>&, const optional<T>&); // 20.5.9, Comparison withnullopt
template <class T> bool operator==(const optional<T>&, nullopt_t) noexcept; template <class T> bool operator==(nullopt_t, const optional<T>&) noexcept; template <class T> bool operator!=(const optional<T>&, nullopt_t) noexcept; template <class T> bool operator!=(nullopt_t, const optional<T>&) noexcept; template <class T> bool operator<(const optional<T>&, nullopt_t) noexcept; template <class T> bool operator<(nullopt_t, const optional<T>&) noexcept; template <class T> bool operator<=(const optional<T>&, nullopt_t) noexcept; template <class T> bool operator<=(nullopt_t, const optional<T>&) noexcept; template <class T> bool operator>(const optional<T>&, nullopt_t) noexcept; template <class T> bool operator>(nullopt_t, const optional<T>&) noexcept; template <class T> bool operator>=(const optional<T>&, nullopt_t) noexcept; template <class T> bool operator>=(nullopt_t, const optional<T>&) noexcept; // 20.5.10, Poisoned comparison with T template <class T> bool operator==(const optional<T>&, const T&) noexcept; template <class T> bool operator==(const T&, const optional<T>&) noexcept; template <class T> bool operator!=(const optional<T>&, const T&) noexcept; template <class T> bool operator!=(const T&, const optional<T>&) noexcept; template <class T> bool operator<(const optional<T>&, const T&) noexcept; template <class T> bool operator<(const T&, const optional<T>&) noexcept; template <class T> bool operator<=(const optional<T>&, const T&) noexcept; template <class T> bool operator<=(const T&, const optional<T>&) noexcept; template <class T> bool operator>(const optional<T>&, const T&) noexcept; template <class T> bool operator>(const T&, const optional<T>&) noexcept; template <class T> bool operator>=(const optional<T>&, const T&) noexcept; template <class T> bool operator>=(const T&, const optional<T>&) noexcept; // 20.5.11, Specialized algorithms template <class T> void swap(optional<T>&, optional<T>&) noexcept(see below); template <class T, class V> typename decay<T>::type get_value_or(const optional<T>&, V&&); template <class T, class V> typename decay<T>::type get_value_or(optional<T>&&, V&&); template <class T> optional<see below> make_optional(T&&); } // namespace experimental } // namespace stdA program that necessitates the instantiation of template
optional
for an rvalue reference type, or for typesemplace_t
ornullopt_t
, or a possibli cv-qualified reference to typesemplace_t
ornullopt_t
is ill-formed.20.5.3 Definitions [optional.defs]
An instance of
optional<T>
is said to be disengaged if it has been default constructed, constructed or assigned with a value of typenullopt_t
, constructed or assigned with a disengaged optional object of typeoptional<U>
, withU
being equal or not toT
.An instance of
optional<T>
is said to be engaged if it has been modified with member functionemplace
, constructed with a value of typeU
, assigned a value of typeU
, copy-constructed from or assigned with an engaged optional object of typeoptional<U>
, whereU
is same as or convertible toT
.Being engaged or disengaged is part of the state optional object's state.
In several places in this Clause the expression
OnlyExplicitlyConstructible(T, V)
is used. All such cases mean the evaluation of the expression:std::is_constructible<T, V>::value && !std::is_convertible<V, T>::value20.5.4
optional
for object types [optional.object]namespace std { namespace experimental { template <class T> class optional { public: typedef T value_type; // 20.5.4.1, constructors constexpr optional() noexcept; constexpr optional(nullopt_t) noexcept; optional(const optional&); optional(optional&&) noexcept(see below); optional(const T&); optional(T&&); template <class... Args> explicit optional(emplace_t, Args&&...); template <class U, class... Args> explicit optional(emplace_t, initializer_list<U>, Args&&...); // 20.5.4.2, destructor ~optional(); // 20.5.4.3, assignment optional& operator=(nullopt_t) noexcept; optional& operator=(const optional&); optional& operator=(optional&&) noexcept(see below); template <class U> optional& operator=(U&&); template <class... Args> optional& emplace(Args&&...); template <class U, class... Args> optional& emplace(initializer_list<U>, Args&&...); // 20.5.4.4, swap void swap(optional&) noexcept(see below); // 20.5.4.5, observers T const* operator ->() const; T* operator ->(); T const& operator *() const; T& operator *(); explicit operator bool() const noexcept; private: bool init; // exposition only T* val; // exposition only }; } // namespace experimental } // namespace stdEngaged instances of
optional<T>
whereT
is of object type shall contain a value of typeT
within its own storage. This value is referred to as the contained value of the optional object. Implementations are not permitted to use additional storage, such as dynamic memory, to allocate its contained value. The contained value shall be allocated in a region of theoptional<T>
storage suitably aligned for the typeT
. Initializing the contained value shall put the optional object into engaged state. Destroying the contained value shall put the optional object into disengaged state.Members
init
andval
are provided for exposition only. Implementations need not provide those members.init
indicates whether theoptional
object's contained value has been initialized (and not yet destroyed);val
points to (a possibly uninitialized) contained value.
T
shall be an object type and shall satisfy the requirements ofDestructible
(Table 24).Throughout this subclause term direct-non-list-initialization is used to denote a direct-initialization that is not list-initialization.
20.5.4.1 Constructors [optional.object.ctor]
constexpr optional<T>::optional() noexcept;
constexpr optional<T>::optional(nullopt_t) noexcept;
- Effects:
Constructs a disengaged
optional
object.- Postconditions:
bool(*this) == false
.- Remarks:
No
T
object referenced is initialized. For every object typeT
these constructors shall beconstexpr
constructors (7.1.5).
optional<T>::optional(const optional<T>& rhs);
- Requires:
is_copy_constructible<T>::value
istrue
.- Effects:
Constructs an
optional
object. Ifbool(rhs) == true
initializes the contained value as if direct-non-list-initializing an object of typeT
with the expression*rhs
.- Postconditions:
If
bool(rhs) == false
thenbool(*this) == false
; otherwisebool(*this) == true
and*(*this)
is equivalent to*rhs
.- Throws:
Whatever the execution of
T
's constructor selected for the copy throws.
optional<T>::optional(optional<T> && rhs) noexcept(see below);
- Requires:
is_move_constructible<T>::value
istrue
.- Effects:
Constructs an
optional
object. Ifbool(rhs) == true
initializes the contained value as if direct-non-list-initializing an object of typeT
with the expressionstd::move(*rhs)
.- Postconditions:
If initially
bool(rhs) == false
thenbool(*this) == false
andbool(rhs) == false
; otherwisebool(*this) == true
and*(*this)
is equivalent to the value*rhs
had initially andbool(rhs) == true
.- Throws:
Whatever the execution of
T
's constructor selected for the copy throws.- Remarks:
The expression inside
noexcept
is equivalent to:is_nothrow_move_constructible<T>::value
optional<T>::optional(const T& v);
- Requires:
is_copy_constructible<T>::value
istrue
.- Effects:
Constructs an
optional
object by direct-non-list-initializing the contained value with the expressionv
.- Postconditions:
bool(*this) == true
and*(*this)
is equivalent tov
.- Throws:
Whatever the execution of
T
's constructor selected for the copy throws.
optional<T>::optional(T&& v);
- Requires:
is_move_constructible<T>::value
istrue
.- Effects:
Constructs an
optional
object by direct-non-list-initializing the contained value with the expressionstd::move(v)
.- Postconditions:
bool(*this) == true
and*(*this)
is equivalent to value thatv
had initially.- Throws:
Whatever the execution of
T
's constructor selected for the move throws.
template <class... Args> explicit optional(emplace_t, Args&&... args);
- Requires:
is_constructible<T, Args&&...>::value
istrue
.- Effects:
Constructs an engaged
optional
object. Initializes the contained value as if constructing an object of type T with the argumentsstd::forward<Args>(args)...
.- Postconditions:
bool(*this) == true
.- Throws:
Whatever the execution of
T
's constructor selected for the initialization throws.
template <class U, class... Args>
explicit optional(emplace_t, initializer_list<U> il, Args&&... args);
- Requires:
is_constructible<T, initializer_list<U>, Args&&...>::value
istrue
.- Effects:
Constructs an engaged
optional
object. Initializes the contained value as if constructing an object of type T with the argumentsil, std::forward<Args>(args)...
.- Postconditions:
bool(*this) == true
.- Throws:
Whatever the execution of
T
's constructor selected for the initialization throws.- Remarks:
The function shall not participate in overload resolution unless
is_constructible<T, initializer_list<U>, Args&&...>::value
istrue
.20.5.4.2 Destructor [optional.object.dtor]
optional<T>::~optional();
- Effects:
If
bool(*this) == true
, callsval->T::~T()
. Destroys theoptional
object.20.5.4.3 Assignment [optional.object.assign]
optional<T>& optional<T>::operator=(nullopt_t) noexcept;
- Effects:
If
bool(*this) == true
callsval->T::~T()
to destroy the contained value; otherwise no effect.- Returns:
*this
- Postconditions:
bool(*this) == false
.
optional<T>& optional<T>::operator=(const optional<T>& rhs);
- Requires:
is_copy_constructible<T>::value
istrue
andis_copy_assignable<T>::value
istrue
.- Effects:
If
init == false && rhs.init == false
, no effect. Ifinit == true && rhs.init == false
, destroys the contained value by callingval->T::~T()
. Ifinit == false && rhs.init == true
, constructs the contained value as if direct-non-list-initializing an object of typeT
with*rhs
. Ifinit == true && rhs.init == true
, assigns*rhs
to the contained value.- Returns:
*this
- Postconditions:
If
bool(rhs) == false
thenbool(*this) == false
; otherwisebool(*this) == true
and*(*this)
is equivalent to*rhs
.- Exception Safety:
If any exception is thrown values of
init
andrhs.init
remain unchanged. If an exception is thrown during the call toT
's copy constructor, no effect. If an exception is thrown during the call toT
's copy assignment, the state of its contained value is as defined by the exception safety guarantee ofT
's copy constructor.
optional<T>& optional<T>::operator=(optional<T>&& rhs) noexcept(see below);
- Requires:
is_move_constructible<T>::value
istrue
andis_move_assignable<T>::value
istrue
.- Effects:
If
init == false && rhs.init == false
, no effect. Ifinit == true && rhs.init == false
, destroys the contained value by callingval->T::~T()
. Ifinit == false && rhs.init == true
, constructs the contained value as if direct-non-list-initializing an object of typeT
withstd::move(*rhs)
. Ifinit == true && rhs.init == true
, assignsstd::move(*rhs)
to the contained value.- Returns:
*this
- Postconditions:
If initially
bool(rhs) == false
thenbool(*this) == false
andbool(rhs) == false
; otherwisebool(*this) == true
and*(*this)
is equivalent to the value that*rhs
had initially andbool(rhs) == true
.- Remarks:
The expression inside
noexcept
is equivalent to:is_nothrow_move_assignable<T>::value && is_nothrow_move_constructible<T>::value- Exception Safety:
If any exception is thrown values of
init
andrhs.init
remain unchanged. If an exception is thrown during the call toT
's move constructor, the state of*rhs.val
is determined by exception safety guarantee ofT
's move constructor. If an exception is thrown during the call toT
's move assignment, the state of*val
and*rhs.val
is determined by exception safety guarantee ofT
's move assignment.
template <class U> optional<T>& optional<T>::operator=(U&& v);
- Requires:
is_constructible<T, U>::value
istrue
andis_assignable<U, T>::value
istrue
.- Effects:
If
bool(*this) == true
assignsstd::forward<U>(v)
to the contained value; otherwise constructs the contained value as if direct-non-list-initializing object of typeT
withstd::forward<U>(v)
.- Returns:
*this
- Postconditions:
bool(*this) == true
and*(*this)
is equivalent to the value thatv
had initially.- Exception Safety:
If any exception is thrown value of
init
remains unchanged. If an exception is thrown during the call toT
's constructor, the state ofv
is determined by exception safety guarantee ofT
's constructor. If an exception is thrown during the call toT
's assignment, the state of*val
andv
is determined by exception safety guarantee ofT
's assignment.- Remarks:
The function shall not participate in overload resolution unless
is_same<typename remove_reference<U>::type, T>::value
istrue
.[Note: The reson to provide such genereic assignment and then constraining it so that effectively
T
==U
is to guarantee that assignment of the formo = {}
is unambiguous. —end note]
template <class... Args> optional<T>& optional<T>::emplace(Args&&... args);
- Requires:
is_constructible<T, Args&&...>::value
istrue
.- Effects:
Calls
*this = nullopt
. Then initializes the contained value as if constructing an object of typeT
with the argumentsstd::forward<Args>(args)...
.- Returns:
*this
- Postconditions:
bool(*this) == true
.- Throws:
Whatever expression
T(std::forward<Args>(args)...)
throws.- Exception Safety:
If an exception is thrown during the call to
T
's constructor,*this
is disengaged, and the previous*val
(if any) has been destroyed.
template <class U, class... Args> optional<T>& optional<T>::emplace(initializer_list<U> il, Args&&... args);
- Requires:
is_constructible<T, initializer_list<U>, Args&&...>::value
istrue
.- Effects:
Calls
*this = nullopt
. Then initializes the contained value as if constructing an object of typeT
with the argumentsil, std::forward<Args>(args)...
.- Returns:
*this
- Postconditions:
bool(*this) == true
.- Throws:
Whatever expression
T(il, std::forward<Args>(args)...)
throws.- Exception Safety:
If an exception is thrown during the call to
T
's constructor,*this
is disengaged, and the previous*val
(if any) has been destroyed.- Remarks:
The function shall not participate in overload resolution unless
is_constructible<T, initializer_list<U>, Args&&...>::value
istrue
.20.5.4.4 Swap [optional.object.swap]
void optional<T>::swap(optional<T>& rhs) noexcept(see below);
- Requires:
T
shall be swappable for lvalues andis_move_constructible<T>::value
istrue
.- Effects:
If
init == false && rhs.init == false
, no effect. Ifinit == true && rhs.init == false
, constructs the contained value ofrhs
by direct-initialization withstd::move(*(*this))
, followed byval->T::~T(), swap(init, rhs.init)
. Ifinit == false && rhs.init == true
, constructs the contained value of*this
by direct-initialization withstd::move(*rhs)
, followed byrhs.val->T::~T(), swap(init, rhs.init)
. Ifinit == true && rhs.init == true
, callsswap(*(*this), *rhs)
.- Throws:
Whatever expressions
swap(declval<T&>(), declval<T&>())
andT{move(declval<T&&>())}
throw.- Remarks:
The expression inside
noexcept
is equivalent to:is_nothrow_move_constructible<T>::value && noexcept(swap(declval<T&>(), declval<T&>()))- Exception Safety:
If any exception is thrown values of
init
andrhs.init
remain unchanged. If an exception is thrown during the call to functionswap
the state of*val
and*rhs.val
is determined by the exception safety quarantee ofswap
for lvalues ofT
. If an exception is thrown durning the call toT
's move constructor, the state of*val
and*rhs.val
is determined by the exception safety quarantee ofT
's move constructor.20.5.4.5 Observers [optional.object.observe]
T const* optional<T>::operator->() const;
T* optional<T>::operator->();
- Requires:
bool(*this) == true
.- Returns:
val
- Throws:
nothing.
T const& optional<T>::operator*() const;
T& optional<T>::operator*();
- Requires:
bool(*this) == true
.- Returns:
*val
- Throws:
nothing.
explicit optional<T>::operator bool() noexcept;
- Returns:
init
20.5.5
optional
for lvalue reference types [optional.lref]namespace std { namespace experimental { template <class T> class optional<T&> { public: typedef T& value_type; // 20.5.5.1, construction/destruction constexpr optional() noexcept; constexpr optional(nullopt_t) noexcept; optional(T&) noexcept; optional(T&&) = delete; optional(const optional&) noexcept; template <class U> optional(const optional<U&>&) noexcept; explicit optional(emplace_t, T&) noexcept; explicit optional(emplace_t, T&&) = delete; ~optional() = default; // 20.5.5.2, mutation optional& operator=(nullopt_t) noexcept; optional& operator=(optional&&) = delete; optional& operator=(const optional&) = delete; optional& emplace(T&) noexcept; optional& emplace(T&&) = delete; // 20.5.5.3, observers T* operator->() const; T& operator*() const; explicit operator bool() const noexcept; private: T* ref; // exposition only }; } // namespace experimental } // namespace stdEngaged instances of
optional<T>
whereT
is of lvalue reference type, refer to objects of typestd::remove_reference<T>::type
, but their life-time is not connected to the life-time of the referred to object. Destroying or disengageing the optional object does not affect the state of the referred to object.Member
ref
is provided for exposition only. Implementations need not provide this member. Ifref == nullptr
, optional object is disengaged; otherwiseref
points to a valid object.20.5.5.1 Construction and destruction [optional.lref.ctor]
constexpr optional<T&>::optional() noexcept;
constexpr optional<T&>::optional(nullopt_t) noexcept;
- Effects:
Constructs a disengaged
optional
object by initializingref
withnullptr
.- Postconditions:
bool(*this) == false
.- Remarks:
For every object type
T
these constructors shall beconstexpr
constructors (7.1.5).
optional<T&>::optional(T& v) noexcept;
- Effects:
Constructs an engaged
optional
object by initializingref
withaddressof(v)
.- Postconditions:
bool(*this) == true && addressof(*(*this)) == addressof(v)
.
optional<T&>::optional(const optional& rhs) noexcept;
template <class U> optional<T&>::optional(const optional<U&>& rhs) noexcept;
- Requires:
is_base_of<T, U>::value == true
, andis_convertible<U&, T&>::value
istrue
.- Effects:
If
rhs
is disengaged, initializesref
withnullptr
; otherwise, constructs an engaged object by initializingref
withaddressof(*rhs)
.- Postconditions:
If
bool(rhs) == true
, thenbool(*this) == true && addressof(*(*this)) == addressof(*rhs)
; otherwisebool(*this) == false
.
explicit optional<T&>::optional(emplace_t, T& v) noexcept;
- Effects:
Constructs an engaged
optional
object by initializingref
withaddressof(v)
.- Postconditions:
bool(*this) == true && addressof(*(*this)) == addressof(v)
.
optional<T&>::~optional() = default;
- Effects:
No effect. This destructor shall be a trivial destructor.
20.5.5.2 Mutation [optional.lref.mutate]
optional<T&>& optional<T&>::operator=(nullopt_t) noexcept;
- Effects:
Assigns
ref
with a value ofnullptr
. Ifref
was non-null initially, the object it referred to is unaffected.- Returns:
*this
.- Postconditions:
bool(*this) == false
.
optional<T&>& optional<T&>::emplace(T& v) noexcept;
- Effects:
Assigns
ref
with a value ofaddressof(v)
. Ifref
was non-null initially, the object it referred to is unaffected.- Returns:
*this
.- Postconditions:
bool(*this) == true && addressof(*(*this)) == addressof(v)
.- Remarks:
If
*this
was engaged before the call the object it referred to is not affected.20.5.5.3 Observers [optional.lref.observe]
T* optional<T&>::operator->() const;
- Requires:
bool(*this) == true
.- Returns:
ref
.- Throws:
nothing.
T& optional<T&>::operator*() const;
- Requires:
bool(*this) == true
.- Returns:
*ref
- Throws:
nothing.
explicit optional<T&>::operator bool() noexcept;
- Returns:
ref != nullptr
20.5.6 In-place construction [optional.inplace]
struct emplace_t{};
constexpr emplace_t emplace{};The struct
emplace_t
is a disengaged structure type used as a unique type to disambiguate constructor and function overloading. Specifically,optional<T>
has a constructor withemplace_t
as the first argument followed by an argument pack; this indicates thatT
should be constructed in-place (as if by a call to placement new expression) with forwarded argument pack as parameters.20.5.7 Disengaged state indicator [optional.nullopt]
struct nullopt_t{see below};
constexpr nullopt_t nullopt(unspecified);The struct
nullopt_t
is an empty structure type used as a unique type to indicate a disengaged state foroptional
objects. In particular,optional<T>
has a constructor withnullopt_t
as single argument; this indicates that a disengaged optional object shall be constructed.Type
nullopt_t
shall not have a default constructor. It shall be a literal type. Constantnullopt
shall be initialized with argument of literal type.20.5.8 Relational operators [optional.relops]
template <class T> bool operator==(const optional<T>& x, const optional<T>& y);
- Requires:
T
shall meet the requirements ofEqualityComparable
.- Returns:
If
bool(x) != bool(y)
,false
; otherwise ifbool(x) == false
,true
; otherwise*x == *y
.
template <class T> bool operator!=(const optional<T>& x, const optional<T>& y);
- Returns:
!(x == y)
.
template <class T> bool operator<(const optional<T>& x, const optional<T>& y);
- Requires:
T
shall meet the requirements ofLessThanComparable
.- Returns:
If
(!y)
,false
; otherwise, if(!x)
,true
; otherwise*x < *y
.
template <class T> bool operator>(const optional<T>& x, const optional<T>& y);
- Returns:
(y < x)
.
template <class T> bool operator<=(const optional<T>& x, const optional<T>& y);
- Returns:
!(y < x)
.
template <class T> bool operator>=(const optional<T>& x, const optional<T>& y);
- Returns:
!(x < y)
.20.5.9 Comparison with
nullopt
[optional.nullops]
template <class T> bool operator==(const optional<T>& x, nullopt_t) noexcept;
template <class T> bool operator==(nullopt_t, const optional<T>& x) noexcept;
- Returns:
(!x)
.
template <class T> bool operator!=(const optional<T>& x, nullopt_t) noexcept;
template <class T> bool operator!=(nullopt_t, const optional<T>& x) noexcept;
- Returns:
bool(x)
.
template <class T> bool operator<(const optional<T>& x, nullopt_t) noexcept;
- Returns:
false
.
template <class T> bool operator<(nullopt_t, const optional<T>& x) noexcept;
- Returns:
bool(x)
.
template <class T> bool operator<=(const optional<T>& x, nullopt_t) noexcept;
- Returns:
(!x)
.
template <class T> bool operator<=(nullopt_t, const optional<T>& x) noexcept;
- Returns:
true
.
template <class T> bool operator>(const optional<T>& x, nullopt_t) noexcept;
- Returns:
bool(x)
.
template <class T> bool operator>(nullopt_t, const optional<T>& x) noexcept;
- Returns:
false
.
template <class T> bool operator>=(const optional<T>& x, nullopt_t) noexcept;
- Returns:
true
.
template <class T> bool operator>=(nullopt_t, const optional<T>& x) noexcept;
- Returns:
(!x)
.20.5.10 Poisoned comparison with
T
[optional.poisoned_comp]
template <class T> bool operator==(const optional<T>&, const T&) noexcept;
template <class T> bool operator==(const T&, const optional<T>&) noexcept;
template <class T> bool operator!=(const optional<T>&, const T&) noexcept;
template <class T> bool operator!=(const T&, const optional<T>&) noexcept;
template <class T> bool operator<(const optional<T>&, const T&) noexcept;
template <class T> bool operator<(const T&, const optional<T>&) noexcept;
template <class T> bool operator<=(const optional<T>&, const T&) noexcept;
template <class T> bool operator<=(const T&, const optional<T>&) noexcept;
template <class T> bool operator>(const optional<T>&, const T&) noexcept;
template <class T> bool operator>(const T&, const optional<T>&) noexcept;
template <class T> bool operator>=(const optional<T>&, const T&) noexcept;
template <class T> bool operator>=(const T&, const optional<T>&) noexcept;
- Remarks:
Program that causes the instantiation of one of the above templates is ill-formed.
20.5.11 Specialized algorithms [optional.specalg]
template <class T> void swap(optional<T>& x, optional<T>& y) noexcept(noexcept(x.swap(y)));
- Requires:
is_reference<T>::value == false
.- Effects:
calls
x.swap(y)
.
template <class T, class V>
typename decay<T>::type get_value_or(const optional<T>& op, V&& v);
- Requires:
is_copy_constructible<T>::value
istrue
andis_convertible<V&&, T>::value
istrue
.- Returns:
op ? *op : static_cast<T>(std::forward<V>(v))
.
template <class T, class V>
typename decay<T>::type get_value_or(optional<T>&& op, V&& v);
- Requires:
is_move_constructible<T>::value
istrue
andis_convertible<V&&, T>::value
istrue
.- Returns:
op ? std::move(*op) : static_cast<T>(std::forward<V>(v))
.- Remarks:
This function provides the same exception safety as
T
's move-constructor.
template <class T>
optional<V> make_optional(T&& v);
- Returns:
optional<V>(std::forward<T>(v))
,
whereV
is defined asX&
ifT
equalsreference_wrapper<X>
; otherwiseV
istypename decay<T>::type
.
This proposal can be implemented as pure library extension, without any compiler magic support, in C++11. Below we perovide a reference implementation that has been tested in GCC 4.6.3 and Clang 3.2.
# include <utility> # include <type_traits> # include <initializer_list> # include <cassert> # define REQUIRES(...) typename enable_if<__VA_ARGS__::value, bool>::type = false namespace std{ // workaround for missing traits in GCC and CLANG template <class T> struct is_nothrow_move_constructible { constexpr static bool value = std::is_nothrow_constructible<T, T&&>::value; }; template <class T, class U> struct is_assignable { template <class X, class Y> static constexpr bool has_assign(...) { return false; } template <class X, class Y, size_t S = sizeof(std::declval<X>() = std::declval<Y>()) > static constexpr bool has_assign(bool) { return true; } constexpr static bool value = has_assign<T, U>(true); }; template <class T> struct is_nothrow_move_assignable { template <class X, bool has_any_move_massign> struct has_nothrow_move_assign { constexpr static bool value = false; }; template <class X> struct has_nothrow_move_assign<X, true> { constexpr static bool value = noexcept( std::declval<X&>() = std::declval<X&&>() ); }; constexpr static bool value = has_nothrow_move_assign<T, is_assignable<T&, T&&>::value>::value; }; // end workaround namespace experimental{ // 20.5.4, optional for object types template <class T> class optional; // 20.5.5, optional for lvalue reference types template <class T> class optional<T&>; template <class T, class U> struct is_explicitly_convertible { constexpr static bool value = std::is_constructible<U, T>::value && !std::is_convertible<T, U>::value; }; template <class U> struct is_not_optional { constexpr static bool value = true; }; template <class T> struct is_not_optional<optional<T>> { constexpr static bool value = false; }; constexpr struct trivial_init_t{} trivial_init{}; // 20.5.6, In-place construction constexpr struct emplace_t{} emplace{}; // 20.5.7, Disengaged state indicator struct nullopt_t { struct init{}; constexpr nullopt_t(init){}; }; constexpr nullopt_t nullopt{nullopt_t::init{}}; template <class T> union storage_t { unsigned char dummy_; T value_; constexpr storage_t( trivial_init_t ) : dummy_() {}; template <class... Args> storage_t( Args&&... args ) : value_(std::forward<Args>(args)...) {} storage_t() : value_() {} // GCC bug workaround ~storage_t(){} }; template <class T> class optional { static_assert( !std::is_same<T, nullopt_t>::value, "bad T" ); static_assert( !std::is_same<T, emplace_t>::value, "bad T" ); bool init_; storage_t<T> storage_; bool initialized() const noexcept { return init_; } T* dataptr() { return std::addressof(storage_.value_); } const T* dataptr() const { return std::addressof(storage_.value_); } void clear() noexcept { if (initialized()) dataptr()->T::~T(); init_ = false; } template <class... Args> void initialize(Args&&... args) noexcept(noexcept(T(std::forward<Args>(args)...))) { assert(!init_); ::new (static_cast<void*>(dataptr())) T(std::forward<Args>(args)...); init_ = true; } template <class U, class... Args> void initialize(std::initializer_list<U> il, Args&&... args) noexcept(noexcept(T(std::forward<Args>(args)...))) { assert(!init_); ::new (static_cast<void*>(dataptr())) T(il, std::forward<Args>(args)...); init_ = true; } public: typedef T value_type; // 20.5.5.1, constructors constexpr optional() noexcept : init_(false), storage_(trivial_init) {}; constexpr optional(nullopt_t) noexcept : init_(false), storage_(trivial_init) {}; optional(const optional& rhs) : init_(rhs.initialized()) { if (rhs.initialized()) ::new (static_cast<void*>(dataptr())) T(*rhs); } optional(optional&& rhs) noexcept(std::is_nothrow_move_constructible<T>::value) : init_(rhs.initialized()) { if (rhs.initialized()) ::new (static_cast<void*>(dataptr())) T(std::move(*rhs)); } optional(const T& v) : init_(true), storage_(v) {} optional(T&& v) : init_(true), storage_(std::move(v)) {} template <class... Args> explicit optional(emplace_t, Args&&... args) : init_(true), storage_(std::forward<Args>(args)...) {} template <class U, class... Args, REQUIRES(is_constructible<T, std::initializer_list<U>>)> explicit optional(emplace_t, std::initializer_list<U> il, Args&&... args) : init_(true), storage_(il, std::forward<Args>(args)...) {} // 20.5.4.2 Destructor ~optional() { if (initialized()) dataptr()->T::~T(); } // 20.5.4.3, assignment optional& operator=(nullopt_t) noexcept { clear(); return *this; } optional& operator=(const optional& rhs) { if (init_ == true && rhs.init_ == false) clear(); else if (init_ == false && rhs.init_ == true) initialize(*rhs); else if (init_ == true && rhs.init_ == true) *dataptr() = *rhs; return *this; } optional& operator=(optional&& rhs) noexcept(std::is_nothrow_move_assignable<T>::value && std::is_nothrow_move_constructible<T>::value) { if (init_ == true && rhs.init_ == false) clear(); else if (init_ == false && rhs.init_ == true) initialize(std::move(*rhs)); else if (init_ == true && rhs.init_ == true) *dataptr() = std::move(*rhs); return *this; } template <class U> auto operator=(U&& v) -> typename enable_if < is_same<typename remove_reference<U>::type, T>::value, optional& >::type { if (initialized()) { *dataptr() = std::forward<U>(v); } else { initialize(std::forward<U>(v)); } return *this; } template <class... Args> optional<T>& emplace(Args&&... args) { clear(); initialize(std::forward<Args>(args)...); return *this; } template <class U, class... Args> optional<T>& emplace(initializer_list<U> il, Args&&... args) { clear(); initialize<U, Args...>(il, std::forward<Args>(args)...); return *this; } // 20.5.4.4 Swap void swap(optional<T>& rhs) noexcept(is_nothrow_move_constructible<T>::value && noexcept(swap(declval<T&>(), declval<T&>()))) { if (init_ == true && rhs.init_ == false) { rhs.initialize(std::move(**this)); clear(); } else if (init_ == false && rhs.init_ == true) { initialize(std::move(*rhs)); rhs.clear(); } else if (init_ == true && rhs.init_ == true) { using std::swap; swap(**this, *rhs); } } // 20.5.4.5 Observers T const* operator ->() const { assert (initialized()); return dataptr(); } T* operator ->() { assert (initialized()); return dataptr(); } T const& operator *() const { assert (initialized()); return *dataptr(); } T& operator *() { assert (initialized()); return *dataptr(); } explicit operator bool() const noexcept { return initialized(); } }; template <class T> class optional<T&> { static_assert( !std::is_same<T, nullopt_t>::value, "bad T" ); static_assert( !std::is_same<T, emplace_t>::value, "bad T" ); T* ref; public: // 20.5.5.1, construction/destruction constexpr optional() : ref(nullptr) {} constexpr optional(nullopt_t) : ref(nullptr) {} optional(T& v) noexcept : ref(&v) {} optional(T&&) = delete; optional(const optional& rhs) noexcept : ref(rhs.ref) {} template <class U> optional(const optional<U&>& rhs) noexcept : ref(rhs.ref) {} explicit optional(emplace_t, T& v) noexcept : ref(&v) {} explicit optional(emplace_t, T&&) = delete; ~optional() = default; // 20.5.5.2, mutation optional& operator=(nullopt_t) noexcept { ref = nullptr; return *this; } optional& operator=(optional&&) = delete; optional& operator=(const optional&) = delete; optional& emplace(T& v) noexcept { ref = &v; return *this; } optional& emplace(T&&) = delete; // 20.5.5.3, observers T* operator->() const { assert (ref); return ref; } T& operator*() const { assert (ref); return *ref; } explicit operator bool() const noexcept { return ref != nullptr; } }; template <class T> class optional<T&&> { static_assert( sizeof(T) == 0, "optional rvalue referencs disallowed" ); }; // 20.5.8, Relational operators template <class T> bool operator==(const optional<T>& x, const optional<T>& y) { return bool(x) != bool(y) ? false : bool(x) == false ? true : *x == *y; } template <class T> bool operator!=(const optional<T>& x, const optional<T>& y) { return !(x == y); } template <class T> bool operator<(const optional<T>& x, const optional<T>& y) { return (!y) ? false : (!x) ? true : *x < *y; } template <class T> bool operator>(const optional<T>& x, const optional<T>& y) { return (y < x); } template <class T> bool operator<=(const optional<T>& x, const optional<T>& y) { return !(y < x); } template <class T> bool operator>=(const optional<T>& x, const optional<T>& y) { return !(x < y); } // 20.5.9 Comparison with nullopt template <class T> bool operator==(const optional<T>& x, nullopt_t) noexcept { return (!x); } template <class T> bool operator==(nullopt_t, const optional<T>& x) noexcept { return (!x); } template <class T> bool operator!=(const optional<T>& x, nullopt_t) noexcept { return bool(x); } template <class T> bool operator!=(nullopt_t, const optional<T>& x) noexcept { return bool(x); } template <class T> bool operator<(const optional<T>&, nullopt_t) noexcept { return false; } template <class T> bool operator<(nullopt_t, const optional<T>& x) noexcept { return bool(x); } template <class T> bool operator<=(const optional<T>& x, nullopt_t) noexcept { return (!x); } template <class T> bool operator<=(nullopt_t, const optional<T>&) noexcept { return true; } template <class T> bool operator>(const optional<T>& x, nullopt_t) noexcept { return bool(x); } template <class T> bool operator>(nullopt_t, const optional<T>&) noexcept { return false; } template <class T> bool operator>=(const optional<T>&, nullopt_t) noexcept { return true; } template <class T> bool operator>=(nullopt_t, const optional<T>& x) noexcept { return (!x); } // 20.5.10 Poisoned comparison with T template <class T> void operator==(const optional<T>&, const T&) noexcept { static_assert(sizeof(T) == 0, "comparison between optional<T> and T disallowed"); } template <class T> void operator==(const T&, const optional<T>&) noexcept { static_assert(sizeof(T) == 0, "comparison between optional<T> and T disallowed"); } template <class T> void operator!=(const optional<T>&, const T&) noexcept { static_assert(sizeof(T) == 0, "comparison between optional<T> and T disallowed"); } template <class T> void operator!=(const T&, const optional<T>&) noexcept { static_assert(sizeof(T) == 0, "comparison between optional<T> and T disallowed"); } template <class T> void operator<(const optional<T>&, const T&) noexcept { static_assert(sizeof(T) == 0, "comparison between optional<T> and T disallowed"); } template <class T> void operator<(const T&, const optional<T>&) noexcept { static_assert(sizeof(T) == 0, "comparison between optional<T> and T disallowed"); } template <class T> void operator<=(const optional<T>&, const T&) noexcept { static_assert(sizeof(T) == 0, "comparison between optional<T> and T disallowed"); } template <class T> void operator<=(const T&, const optional<T>&) noexcept { static_assert(sizeof(T) == 0, "comparison between optional<T> and T disallowed"); } template <class T> void operator>(const optional<T>&, const T&) noexcept { static_assert(sizeof(T) == 0, "comparison between optional<T> and T disallowed"); } template <class T> void operator>(const T&, const optional<T>&) noexcept { static_assert(sizeof(T) == 0, "comparison between optional<T> and T disallowed"); } template <class T> void operator>=(const optional<T>&, const T&) noexcept { static_assert(sizeof(T) == 0, "comparison between optional<T> and T disallowed"); } template <class T> void operator>=(const T&, const optional<T>&) noexcept { static_assert(sizeof(T) == 0, "comparison between optional<T> and T disallowed"); } // 20.5.11 Specialized algorithms template <class T> void swap(optional<T>& x, optional<T>& y) noexcept(noexcept(x.swap(y))) { static_assert(!is_reference<T>::value, "no swap for optional refs"); x.swap(y); } template <class T, class V> typename decay<T>::type get_value_or(const optional<T>& op, V&& v) { return op ? *op : static_cast<T>(std::forward<V>(v)); } template <class T, class V> typename decay<T>::type get_value_or(optional<T>&& op, V&& v) { return op ? std::move(*op) : static_cast<T>(std::forward<V>(v)); } template <class T> optional<typename decay<T>::type> make_optional(T&& v) { return optional<typename decay<T>::type>(std::forward<T>(v)); } template <class X> optional<X&> make_optional(reference_wrapper<X> v) { return optional<X&>(v); } } // namespace experimental } // namespace std
Many people from the Boost community, participated in the developement of the Boost.Optional library. Sebastian Redl suggested the usage of function emplace
.
Daniel Krügler provided numerous helpful suggestions, corrections and comments on this paper; in particular he suggested the addition of and reference implementation for "perfect initialization" operations.
People in discussion group "ISO C++ Standard - Future Proposals" provided numerous insightful suggestions: Vladimir Batov (who described and supported the perfect forwarding constructor), Nevin Liber, Ville Voutilainen, Richard Smiths, Dave Abrahams, Chris Jefferson, Jeffrey Yasskin, Nikolay Ivchenkov, and many more.
noexcept
Prevents Library Validation" (N3248, http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3248.pdf)