mirror of
https://github.com/boostorg/optional.git
synced 2025-07-15 05:16:36 +02:00
Fixed code, updated docs, added emplace()
This commit is contained in:
@ -46,23 +46,39 @@ Distributed under the Boost Software License, Version 1.0.
|
||||
|
||||
|
||||
[section Introduction]
|
||||
This library can be used to represent 'optional' (or 'nullable') objects that can be safely passed by value:
|
||||
|
||||
optional<int> readInt(); // this function may return either an int or a not-an-int
|
||||
|
||||
if (optional<int> oi = readInt()) // did I get a real int
|
||||
cout << "my int is: " << *oi; // use my int
|
||||
else
|
||||
cout << "I have no int";
|
||||
Class template `optional` is a wrapper for representing 'optional' (or 'nullable') objects who may not (yet) contain a valid value. Optional objects offer full value semantics; they are good for passing by value and usage inside STL containers. This is a header-only library.
|
||||
|
||||
[section Problem]
|
||||
Suppose we want to read a parameter form a config file which represents some integral value, let's call it `"MaxValue"`. It is possible that this parameter is not specified; such situation is no error. It is valid to not specify the parameter and in that case the program is supposed to behave slightly different. Also suppose that any possible value of type `int` is a valid value for `"MaxValue"`, so we cannot jut use `-1` to represent the absence of the parameter in the config file.
|
||||
[endsect]
|
||||
|
||||
[include motivation.qbk]
|
||||
[include development.qbk]
|
||||
[include reference.qbk]
|
||||
[include examples.qbk]
|
||||
[include special_cases.qbk]
|
||||
[include dependencies.qbk]
|
||||
[include acknowledgments.qbk]
|
||||
[section Solution]
|
||||
|
||||
This is how you solve it with `boost::optional`:
|
||||
|
||||
#include <boost/optional.hpp>
|
||||
|
||||
boost::optional<int> getConfigParam(std::string name); // return either an int or a `not-an-int`
|
||||
|
||||
int main()
|
||||
{
|
||||
if (boost::optional<int> oi = getConfigParam("MaxValue")) // did I get a real int?
|
||||
runWithMax(*oi); // use my int
|
||||
else
|
||||
runWithNoMax();
|
||||
}
|
||||
|
||||
[endsect]
|
||||
[endsect]
|
||||
|
||||
[include 01_tutorial.qbk]
|
||||
[include 02_discussion.qbk]
|
||||
[include 03_development.qbk]
|
||||
[include 04_reference.qbk]
|
||||
[include 05_examples.qbk]
|
||||
[include 10_optional_references.qbk]
|
||||
[include 11_special_cases.qbk]
|
||||
[include 90_dependencies.qbk]
|
||||
[include 91_acknowledgments.qbk]
|
||||
|
||||
|
113
doc/01_tutorial.qbk
Normal file
113
doc/01_tutorial.qbk
Normal file
@ -0,0 +1,113 @@
|
||||
[/
|
||||
Boost.Optional
|
||||
|
||||
Copyright (c) 2003-2007 Fernando Luis Cacciola Carballal
|
||||
Copyright (c) 2014 Andrzej Krzemienski
|
||||
|
||||
Distributed under the Boost Software License, Version 1.0.
|
||||
(See accompanying file LICENSE_1_0.txt or copy at
|
||||
http://www.boost.org/LICENSE_1_0.txt)
|
||||
]
|
||||
|
||||
|
||||
[section Tutorial]
|
||||
|
||||
[section Optional return values]
|
||||
|
||||
Let's write and use a converter function that converts an a `std::string` to an `int`. It is possible that for a given string (e.g. `"cat"`) there exist no value of type `int` capable of representing the conversion result. We do not consider such situation an error. We expect that the converter can be used only to check if the conversion is possible. A natural signature for this function can be:
|
||||
|
||||
#include <boost/optional.hpp>
|
||||
boost::optionl<int> convert(const std::string& text);
|
||||
|
||||
All necessary functionality can be included with one header `<boost/optional.hpp>`. The above function signature means that the function can either return a value of type `int` or a flag indicating that no value of `int` is available. This does not indicate an error. It is like one additional value of `int`. This is how we can use our function:
|
||||
|
||||
const std::string& text = /*... */;
|
||||
boost::optionl<int> oi = convert(text); // move-construct
|
||||
if (oi) // contextual conversion to bool
|
||||
int i = *oi; // operator*
|
||||
|
||||
In order to test if `optional` contains a value, we use the contextual conversion to type `bool`. Because of this we can combine the initialization of the optional object and the test into one instruction:
|
||||
|
||||
if (boost::optionl<int> oi = convert(text))
|
||||
int i = *oi;
|
||||
|
||||
We extract the contained value with `operator*` (and with `operator->` where it makes sense). An attempt to extract the contained value of an uninitialized optional object is an ['undefined behaviour] (UB). This implementation guards the call with `BOOST_ASSERT`. Therefore you should be sure that the contained value is there before extracting. For instance, the following code is reasonably UB-safe:
|
||||
|
||||
int i = *convert("100");
|
||||
|
||||
This is because we know that string value `"100"` converts to a valid value of `int`. If you do not like this potential UB, you can use an alternative way of extracting the contained value:
|
||||
|
||||
try {
|
||||
int j = convert(text).value();
|
||||
}
|
||||
catch (const boost::bad_optional_access&) {
|
||||
// deal with it
|
||||
}
|
||||
|
||||
This version throws an exception upon an attempt to access a non-existent contained value. If your way of dealing with the missing value is to use some default, like `0`, there exists a yet another alternative:
|
||||
|
||||
int k = convert(text).value_or(0);
|
||||
|
||||
This uses the `atoi`-like approach to conversions: if `text` does not represent an integral number just return `0`. Now, let's consider how function `convert` can be implemented.
|
||||
|
||||
boost::optionl<int> convert(const std::string& text)
|
||||
{
|
||||
std::stringstream s(text);
|
||||
int i;
|
||||
if ((s >> i) && s.get() == std::char_traits<char>::eof())
|
||||
return i;
|
||||
else
|
||||
return boost::none;
|
||||
}
|
||||
|
||||
Observe the two return statements. `return i` uses the converting constructor that can create `optional<T>` from `T`. Thus constructed optional object is initialized and its value is a copy of `i`. The other return statement uses another converting constructor from a special tag `boost::none`. It is used to indicate that we want to create an uninitialized optional object.
|
||||
|
||||
|
||||
[endsect]
|
||||
|
||||
[section Optional data members]
|
||||
Suppose we want to implement a ['lazy load] optimization. This is because we do not want to perform an expensive initialization of our `Resource` until (if at all) it is really used. We can do it this way:
|
||||
|
||||
class Widget
|
||||
{
|
||||
boost::optional<Resource> resource_;
|
||||
|
||||
public:
|
||||
Widget() {}
|
||||
|
||||
Resource& getResource() // not thread-safe
|
||||
{
|
||||
if (resource_ == boost::none)
|
||||
resource_.emplace("resource", "arguments");
|
||||
|
||||
return *resource_;
|
||||
}
|
||||
};
|
||||
|
||||
`optional`'s default constructor creates an uninitialized optional. No call to `Resource`'s default constructor is attempted. `Resource` doesn't have to be __SGI_DEFAULT_CONSTRUCTIBLE__. In function `getResource` we first check if `resource_` is initialized. This time we do not use the contextual conversion to `bool`, but a comparison with `boost::none`. These two ways are equivalent. Function `emplace` initializes the optional in-place by perfect-forwarding the arguments to the constructor of `Resource`. No copy- or move-construction is involved here. `Resource` doesn't even have to be `MoveConstructible`.
|
||||
|
||||
[note Function `emplace` is only available on compilers that support rvalue references and variadic templates. If your compiler does not support these features and you still need to avoid any move-constructions, use [link boost_optional.in_place_factories In-Place Factories].]
|
||||
|
||||
[endsect]
|
||||
|
||||
[section Bypassing unnecessary default construction]
|
||||
Suppose we have class `Date`, which does not have a default constructor: there is no good candidate for a default date. We have a function that returns two dates in form of a `boost::tuple`:
|
||||
|
||||
boost::tuple<Date, Date> getPeriod();
|
||||
|
||||
In other place we want to use the result of `getPeriod`, but want the two dates to be named: `begin` and `end`. We want to implement something like 'multiple return values':
|
||||
|
||||
Date begin, end; // Error: no default ctor!
|
||||
boost::tie(begin, end) = getPeriod();
|
||||
|
||||
The second line works already, this is the capability of Boost.Tuple library, but the first line won't work. We could set some initial invented dates, but it is confusing and may be an unacceptable cost, given that these values will be overwritten in the next line anyway. This is where `optional` can help:
|
||||
|
||||
boost::optional<Date> begin, end;
|
||||
boost::tie(begin, end) = getPeriod();
|
||||
|
||||
It works because inside `boost::tie` a move-assignment from `T` is invoked on `optional<T>`, which internally calls a move-constructor of `T`.
|
||||
[endsect]
|
||||
|
||||
[endsect]
|
||||
|
||||
|
@ -9,7 +9,7 @@
|
||||
http://www.boost.org/LICENSE_1_0.txt)
|
||||
]
|
||||
|
||||
[section Motivation]
|
||||
[section Discussion]
|
||||
|
||||
Consider these functions which should return a value but which might not have
|
||||
a value to return:
|
@ -13,13 +13,13 @@
|
||||
[section The models]
|
||||
|
||||
In C++, we can ['declare] an object (a variable) of type `T`, and we can give this
|
||||
variable an ['initial value] (through an ['initializer]. (c.f. 8.5)).
|
||||
variable an ['initial value] (through an ['initializer]. (cf. 8.5)).
|
||||
When a declaration includes a non-empty initializer (an initial value is given),
|
||||
it is said that the object has been initialized.
|
||||
If the declaration uses an empty initializer (no initial value is given), and
|
||||
neither default nor value initialization applies, it is said that the object is
|
||||
[*uninitialized]. Its actual value exist but has an ['indeterminate initial value]
|
||||
(c.f. 8.5.9).
|
||||
(cf. 8.5/11).
|
||||
`optional<T>` intends to formalize the notion of initialization (or lack of it)
|
||||
allowing a program to test whether an object has been initialized and stating
|
||||
that access to the value of an uninitialized object is undefined behavior. That
|
||||
@ -38,7 +38,7 @@ additional information to tell if an object has been effectively initialized.
|
||||
One of the typical ways in which this has been historically dealt with is via
|
||||
a special value: `EOF`, `npos`, -1, etc... This is equivalent to adding the
|
||||
special value to the set of possible values of a given type. This super set of
|
||||
`T` plus some ['nil_t]—were `nil_t` is some stateless POD-can be modeled in modern
|
||||
`T` plus some ['nil_t]—where `nil_t` is some stateless POD—can be modeled in modern
|
||||
languages as a [*discriminated union] of T and nil_t. Discriminated unions are
|
||||
often called ['variants]. A variant has a ['current type], which in our case is either
|
||||
`T` or `nil_t`.
|
||||
@ -197,7 +197,7 @@ be undefined unless the implied pointee actually exist.
|
||||
Such a ['de facto] idiom for referring to optional objects can be formalized
|
||||
in the form of a concept: the __OPTIONAL_POINTEE__ concept.
|
||||
This concept captures the syntactic usage of operators `*`, `->` and
|
||||
conversion to `bool` to convey the notion of optionality.
|
||||
contextual conversion to `bool` to convey the notion of optionality.
|
||||
|
||||
However, pointers are good to [_refer] to optional objects, but not particularly
|
||||
good to handle the optional objects in all other respects, such as initializing
|
@ -59,6 +59,8 @@
|
||||
|
||||
template<class U> optional& operator = ( optional<U>&& rhs ) ; ``[link reference_optional_operator_move_equal_other_optional __GO_TO__]``
|
||||
|
||||
template<class... Args> void emplace ( Args...&& args ) ; ``[link reference_optional_emplace __GO_TO__]``
|
||||
|
||||
template<class InPlaceFactory> optional& operator = ( InPlaceFactory const& f ) ; ``[link reference_optional_operator_equal_factory __GO_TO__]``
|
||||
|
||||
template<class TypedInPlaceFactory> optional& operator = ( TypedInPlaceFactory const& f ) ; ``[link reference_optional_operator_equal_factory __GO_TO__]``
|
||||
@ -746,6 +748,21 @@ assert ( *opt1 == static_cast<U>(v) ) ;
|
||||
|
||||
__SPACE__
|
||||
|
||||
[#reference_optional_emplace]
|
||||
|
||||
[: `template<class... Args> void optional<T` ['(not a ref)]`>::emplace( Args...&& args );`]
|
||||
|
||||
* [*Requires:] The compiler supports rvalue references and variadic templates.
|
||||
* [*Effect:] If `*this` is initialized calls `*this = none`.
|
||||
Then initializes in-place the contained value as if direct-initializing an object
|
||||
of type `T` with `std::forward<Args>(args)...`.
|
||||
* [*Postconditions: ] `*this` is [_initialized].
|
||||
* [*Throws:] Whatever the selected `T`'s constructor throws.
|
||||
* [*Notes:] `T` need not be `MoveConstructible` or `MoveAssignable`.
|
||||
* [*Exception Safety:] If an exception is thrown during the initialization of `T`, `*this` is ['uninitialized].
|
||||
|
||||
__SPACE__
|
||||
|
||||
[#reference_optional_operator_equal_factory]
|
||||
|
||||
[: `template<InPlaceFactory> optional<T>& optional<T` ['(not a ref)]`>::operator=( InPlaceFactory const& f );`]
|
||||
@ -823,7 +840,7 @@ try {
|
||||
assert ( false );
|
||||
}
|
||||
catch(bad_optional_access&) {
|
||||
asert ( true );
|
||||
assert ( true );
|
||||
}
|
||||
``
|
||||
__SPACE__
|
120
doc/10_optional_references.qbk
Normal file
120
doc/10_optional_references.qbk
Normal file
@ -0,0 +1,120 @@
|
||||
|
||||
[section Optional references]
|
||||
|
||||
This library allows the template parameter `T` to be of reference type:
|
||||
`T&`, and to some extent, `T const&`.
|
||||
|
||||
However, since references are not real objects some restrictions apply and
|
||||
some operations are not available in this case:
|
||||
|
||||
* Converting constructors
|
||||
* Converting assignment
|
||||
* InPlace construction
|
||||
* InPlace assignment
|
||||
* Value-access via pointer
|
||||
|
||||
Also, even though `optional<T&>` treats it wrapped pseudo-object much as
|
||||
a real value, a true real reference is stored so aliasing will ocurr:
|
||||
|
||||
* Copies of `optional<T&>` will copy the references but all these references
|
||||
will nonetheless refer to the same object.
|
||||
* Value-access will actually provide access to the referenced object
|
||||
rather than the reference itself.
|
||||
|
||||
[warning On compilers that do not conform to Standard C++ rules of reference binding, operations on optional references might give adverse results: rather than binding a reference to a designated object they may create an unexpected temporary and bind to it. For more details see [link boost_optional.dependencies_and_portability.optional_reference_binding Dependencies and Portability section].]
|
||||
|
||||
[heading Rvalue references]
|
||||
|
||||
Rvalue references and lvalue references to const have the ability in C++ to extend the life time of a temporary they bind to. Optional references do not have this capability, therefore to avoid surprising effects it is not possible to initialize an optional references from a temporary. Optional rvalue references are disabled altogether. Also, the initialization and assignment of an optional reference to const from rvalue reference is disabled.
|
||||
|
||||
const int& i = 1; // legal
|
||||
optional<const int&> oi = 1; // illegal
|
||||
|
||||
[endsect]
|
||||
|
||||
[section Rebinding semantics for assignment of optional references]
|
||||
|
||||
If you assign to an ['uninitialized ] `optional<T&>` the effect is to bind (for
|
||||
the first time) to the object. Clearly, there is no other choice.
|
||||
|
||||
int x = 1 ;
|
||||
int& rx = x ;
|
||||
optional<int&> ora ;
|
||||
optional<int&> orb(x) ;
|
||||
ora = orb ; // now 'ora' is bound to 'x' through 'rx'
|
||||
*ora = 2 ; // Changes value of 'x' through 'ora'
|
||||
assert(x==2);
|
||||
|
||||
If you assign to a bare C++ reference, the assignment is forwarded to the
|
||||
referenced object; its value changes but the reference is never rebound.
|
||||
|
||||
int a = 1 ;
|
||||
int& ra = a ;
|
||||
int b = 2 ;
|
||||
int& rb = b ;
|
||||
ra = rb ; // Changes the value of 'a' to 'b'
|
||||
assert(a==b);
|
||||
b = 3 ;
|
||||
assert(ra!=b); // 'ra' is not rebound to 'b'
|
||||
|
||||
Now, if you assign to an ['initialized ] `optional<T&>`, the effect is to
|
||||
[*rebind] to the new object instead of assigning the referee. This is unlike
|
||||
bare C++ references.
|
||||
|
||||
int a = 1 ;
|
||||
int b = 2 ;
|
||||
int& ra = a ;
|
||||
int& rb = b ;
|
||||
optional<int&> ora(ra) ;
|
||||
optional<int&> orb(rb) ;
|
||||
ora = orb ; // 'ora' is rebound to 'b'
|
||||
*ora = 3 ; // Changes value of 'b' (not 'a')
|
||||
assert(a==1);
|
||||
assert(b==3);
|
||||
|
||||
[heading Rationale]
|
||||
|
||||
Rebinding semantics for the assignment of ['initialized ] `optional` references has
|
||||
been chosen to provide [*consistency among initialization states] even at the
|
||||
expense of lack of consistency with the semantics of bare C++ references.
|
||||
It is true that `optional<U>` strives to behave as much as possible as `U`
|
||||
does whenever it is initialized; but in the case when `U` is `T&`, doing so would
|
||||
result in inconsistent behavior w.r.t to the lvalue initialization state.
|
||||
|
||||
Imagine `optional<T&>` forwarding assignment to the referenced object (thus
|
||||
changing the referenced object value but not rebinding), and consider the
|
||||
following code:
|
||||
|
||||
optional<int&> a = get();
|
||||
int x = 1 ;
|
||||
int& rx = x ;
|
||||
optional<int&> b(rx);
|
||||
a = b ;
|
||||
|
||||
What does the assignment do?
|
||||
|
||||
If `a` is ['uninitialized], the answer is clear: it binds to `x` (we now have
|
||||
another reference to `x`).
|
||||
But what if `a` is already ['initialized]? it would change the value of the
|
||||
referenced object (whatever that is); which is inconsistent with the other
|
||||
possible case.
|
||||
|
||||
If `optional<T&>` would assign just like `T&` does, you would never be able to
|
||||
use Optional's assignment without explicitly handling the previous
|
||||
initialization state unless your code is capable of functioning whether
|
||||
after the assignment, `a` aliases the same object as `b` or not.
|
||||
|
||||
That is, you would have to discriminate in order to be consistent.
|
||||
|
||||
If in your code rebinding to another object is not an option, then it is very
|
||||
likely that binding for the first time isn't either. In such case, assignment
|
||||
to an ['uninitialized ] `optional<T&>` shall be prohibited. It is quite possible
|
||||
that in such a scenario it is a precondition that the lvalue must be already
|
||||
initialized. If it isn't, then binding for the first time is OK
|
||||
while rebinding is not which is IMO very unlikely.
|
||||
In such a scenario, you can assign the value itself directly, as in:
|
||||
|
||||
assert(!!opt);
|
||||
*opt=value;
|
||||
|
||||
[endsect]
|
@ -1,124 +1,4 @@
|
||||
|
||||
[section Optional references]
|
||||
|
||||
This library allows the template parameter `T` to be of reference type:
|
||||
`T&`, and to some extent, `T const&`.
|
||||
|
||||
However, since references are not real objects some restrictions apply and
|
||||
some operations are not available in this case:
|
||||
|
||||
* Converting constructors
|
||||
* Converting assignment
|
||||
* InPlace construction
|
||||
* InPlace assignment
|
||||
* Value-access via pointer
|
||||
|
||||
Also, even though `optional<T&>` treats it wrapped pseudo-object much as
|
||||
a real value, a true real reference is stored so aliasing will ocurr:
|
||||
|
||||
* Copies of `optional<T&>` will copy the references but all these references
|
||||
will nonetheless refer to the same object.
|
||||
* Value-access will actually provide access to the referenced object
|
||||
rather than the reference itself.
|
||||
|
||||
[warning On compilers that do not conform to Standard C++ rules of reference binding, operations on optional references might give adverse results: rather than binding a reference to a designated object they may create an unexpected temporary and bind to it. For more details see [link boost_optional.dependencies_and_portability.optional_reference_binding Dependencies and Portability section].]
|
||||
|
||||
[heading Rvalue references]
|
||||
|
||||
Rvalue references and lvalue references to const have the ability in C++ to extend the life time of a temporary they bind to. Optional references do not have this capability, therefore to avoid surprising effects it is not possible to initialize an optional references from a temporary. Optional rvalue references are disabled altogether. Also, the initialization and assignment of an optional reference to const from rvalue reference is disabled.
|
||||
|
||||
const int& i = 1; // legal
|
||||
optional<const int&> oi = 1; // illegal
|
||||
|
||||
[endsect]
|
||||
|
||||
[section Rebinding semantics for assignment of optional references]
|
||||
|
||||
If you assign to an ['uninitialized ] `optional<T&>` the effect is to bind (for
|
||||
the first time) to the object. Clearly, there is no other choice.
|
||||
|
||||
int x = 1 ;
|
||||
int& rx = x ;
|
||||
optional<int&> ora ;
|
||||
optional<int&> orb(x) ;
|
||||
ora = orb ; // now 'ora' is bound to 'x' through 'rx'
|
||||
*ora = 2 ; // Changes value of 'x' through 'ora'
|
||||
assert(x==2);
|
||||
|
||||
If you assign to a bare C++ reference, the assignment is forwarded to the
|
||||
referenced object; its value changes but the reference is never rebound.
|
||||
|
||||
int a = 1 ;
|
||||
int& ra = a ;
|
||||
int b = 2 ;
|
||||
int& rb = b ;
|
||||
ra = rb ; // Changes the value of 'a' to 'b'
|
||||
assert(a==b);
|
||||
b = 3 ;
|
||||
assert(ra!=b); // 'ra' is not rebound to 'b'
|
||||
|
||||
Now, if you assign to an ['initialized ] `optional<T&>`, the effect is to
|
||||
[*rebind] to the new object instead of assigning the referee. This is unlike
|
||||
bare C++ references.
|
||||
|
||||
int a = 1 ;
|
||||
int b = 2 ;
|
||||
int& ra = a ;
|
||||
int& rb = b ;
|
||||
optional<int&> ora(ra) ;
|
||||
optional<int&> orb(rb) ;
|
||||
ora = orb ; // 'ora' is rebound to 'b'
|
||||
*ora = 3 ; // Changes value of 'b' (not 'a')
|
||||
assert(a==1);
|
||||
assert(b==3);
|
||||
|
||||
[heading Rationale]
|
||||
|
||||
Rebinding semantics for the assignment of ['initialized ] `optional` references has
|
||||
been chosen to provide [*consistency among initialization states] even at the
|
||||
expense of lack of consistency with the semantics of bare C++ references.
|
||||
It is true that `optional<U>` strives to behave as much as possible as `U`
|
||||
does whenever it is initialized; but in the case when `U` is `T&`, doing so would
|
||||
result in inconsistent behavior w.r.t to the lvalue initialization state.
|
||||
|
||||
Imagine `optional<T&>` forwarding assignment to the referenced object (thus
|
||||
changing the referenced object value but not rebinding), and consider the
|
||||
following code:
|
||||
|
||||
optional<int&> a = get();
|
||||
int x = 1 ;
|
||||
int& rx = x ;
|
||||
optional<int&> b(rx);
|
||||
a = b ;
|
||||
|
||||
What does the assignment do?
|
||||
|
||||
If `a` is ['uninitialized], the answer is clear: it binds to `x` (we now have
|
||||
another reference to `x`).
|
||||
But what if `a` is already ['initialized]? it would change the value of the
|
||||
referenced object (whatever that is); which is inconsistent with the other
|
||||
possible case.
|
||||
|
||||
If `optional<T&>` would assign just like `T&` does, you would never be able to
|
||||
use Optional's assignment without explicitly handling the previous
|
||||
initialization state unless your code is capable of functioning whether
|
||||
after the assignment, `a` aliases the same object as `b` or not.
|
||||
|
||||
That is, you would have to discriminate in order to be consistent.
|
||||
|
||||
If in your code rebinding to another object is not an option, then it is very
|
||||
likely that binding for the first time isn't either. In such case, assignment
|
||||
to an ['uninitialized ] `optional<T&>` shall be prohibited. It is quite possible
|
||||
that in such a scenario it is a precondition that the lvalue must be already
|
||||
initialized. If it isn't, then binding for the first time is OK
|
||||
while rebinding is not which is IMO very unlikely.
|
||||
In such a scenario, you can assign the value itself directly, as in:
|
||||
|
||||
assert(!!opt);
|
||||
*opt=value;
|
||||
|
||||
[endsect]
|
||||
|
||||
[section In-Place Factories]
|
||||
|
||||
One of the typical problems with wrappers and containers is that their
|
||||
@ -356,6 +236,8 @@ Unless `T`'s constructor or assignment throws, assignments to `optional<T>` do n
|
||||
|
||||
This also applies to move assignments/constructors. However, move operations are made no-throw more often.
|
||||
|
||||
Operation `emplace` provides basic exception safety guarantee. If it throws, the optional object becomes uninitialized regardless of its initial state, and its previous contained value (if any) is destroyed. It doesn't call any assignment or move/copy constructor on `T`.
|
||||
|
||||
[heading Swap]
|
||||
|
||||
Unless `swap` on optional is customized, its primary implementation forwards calls to `T`'s `swap` or move constructor (depending on the initialization state of the optional objects). Thus, if both `T`'s `swap` and move constructor never throw, `swap` on `optional<T>` never throws. similarly, if both `T`'s `swap` and move constructor offer strong guarantee, `swap` on `optional<T>` also offers a strong guarantee.
|
||||
@ -365,8 +247,9 @@ In case `swap` on optional is customized, the call to `T`'s move constructor are
|
||||
|
||||
[section Type requirements]
|
||||
|
||||
In general, `T` must be `MoveConstructible` and have a no-throw destructor.
|
||||
The `MoveConstructible` requirement is not needed if [*InPlaceFactories] are used.
|
||||
At the very minimum for `optional<T>` to work with a minimum interface it is required that `T` has a publicly accessible no-throw destructor. In that case you need to initialize the optional object with function `emplace()` or use [*InPlaceFactories].
|
||||
Additionally, if `T` is `Moveable`, `optional<T>` is also `Moveable` and can be easily initialized from an rvalue of type `T` and be passed by value.
|
||||
Additionally if `T` is `Copyable`, `optional<T>` is also `Copyable` and can be easily initialized from an lvalue of type `T`.
|
||||
|
||||
`T` [_is not] required to be __SGI_DEFAULT_CONSTRUCTIBLE__.
|
||||
|
@ -17,7 +17,7 @@ path-constant images : html ;
|
||||
|
||||
xml optional
|
||||
:
|
||||
optional.qbk
|
||||
00_optional.qbk
|
||||
;
|
||||
|
||||
boostbook standalone
|
||||
|
@ -1080,6 +1080,42 @@
|
||||
</pre>
|
||||
</li>
|
||||
</ul></div>
|
||||
<p>
|
||||
<span class="inlinemediaobject"><img src="../images/space.png" alt="space"></span>
|
||||
</p>
|
||||
<a name="reference_optional_emplace"></a><div class="blockquote"><blockquote class="blockquote"><p>
|
||||
<code class="computeroutput"><span class="keyword">template</span><span class="special"><</span><span class="keyword">class</span><span class="special">...</span> <span class="identifier">Args</span><span class="special">></span> <span class="keyword">void</span> <span class="identifier">optional</span><span class="special"><</span><span class="identifier">T</span></code>
|
||||
<span class="emphasis"><em>(not a ref)</em></span><code class="computeroutput"><span class="special">>::</span><span class="identifier">emplace</span><span class="special">(</span> <span class="identifier">Args</span><span class="special">...&&</span>
|
||||
<span class="identifier">args</span> <span class="special">);</span></code>
|
||||
</p></blockquote></div>
|
||||
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
|
||||
<li class="listitem">
|
||||
<span class="bold"><strong>Requires:</strong></span> The compiler supports rvalue
|
||||
references and variadic templates.
|
||||
</li>
|
||||
<li class="listitem">
|
||||
<span class="bold"><strong>Effect:</strong></span> If <code class="computeroutput"><span class="special">*</span><span class="keyword">this</span></code> is initialized calls <code class="computeroutput"><span class="special">*</span><span class="keyword">this</span> <span class="special">=</span>
|
||||
<span class="identifier">none</span></code>. Then initializes in-place
|
||||
the contained value as if direct-initializing an object of type <code class="computeroutput"><span class="identifier">T</span></code> with <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">forward</span><span class="special"><</span><span class="identifier">Args</span><span class="special">>(</span><span class="identifier">args</span><span class="special">)...</span></code>.
|
||||
</li>
|
||||
<li class="listitem">
|
||||
<span class="bold"><strong>Postconditions: </strong></span> <code class="computeroutput"><span class="special">*</span><span class="keyword">this</span></code> is <span class="underline">initialized</span>.
|
||||
</li>
|
||||
<li class="listitem">
|
||||
<span class="bold"><strong>Throws:</strong></span> Whatever the selected <code class="computeroutput"><span class="identifier">T</span></code>'s constructor throws.
|
||||
</li>
|
||||
<li class="listitem">
|
||||
<span class="bold"><strong>Notes:</strong></span> <code class="computeroutput"><span class="identifier">T</span></code>
|
||||
need not be <code class="computeroutput"><span class="identifier">MoveConstructible</span></code>
|
||||
or <code class="computeroutput"><span class="identifier">MoveAssignable</span></code>.
|
||||
</li>
|
||||
<li class="listitem">
|
||||
<span class="bold"><strong>Exception Safety:</strong></span> If an exception is thrown
|
||||
during the initialization of <code class="computeroutput"><span class="identifier">T</span></code>,
|
||||
<code class="computeroutput"><span class="special">*</span><span class="keyword">this</span></code>
|
||||
is <span class="emphasis"><em>uninitialized</em></span>.
|
||||
</li>
|
||||
</ul></div>
|
||||
<p>
|
||||
<span class="inlinemediaobject"><img src="../images/space.png" alt="space"></span>
|
||||
</p>
|
||||
@ -1232,7 +1268,7 @@
|
||||
<span class="identifier">assert</span> <span class="special">(</span> <span class="keyword">false</span> <span class="special">);</span>
|
||||
<span class="special">}</span>
|
||||
<span class="keyword">catch</span><span class="special">(</span><span class="identifier">bad_optional_access</span><span class="special">&)</span> <span class="special">{</span>
|
||||
<span class="identifier">asert</span> <span class="special">(</span> <span class="keyword">true</span> <span class="special">);</span>
|
||||
<span class="identifier">assert</span> <span class="special">(</span> <span class="keyword">true</span> <span class="special">);</span>
|
||||
<span class="special">}</span>
|
||||
</pre>
|
||||
<span class="inlinemediaobject"><img src="../images/space.png" alt="space"></span>
|
||||
|
@ -6,7 +6,7 @@
|
||||
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
|
||||
<link rel="home" href="../index.html" title="Chapter 1. Boost.Optional">
|
||||
<link rel="up" href="../index.html" title="Chapter 1. Boost.Optional">
|
||||
<link rel="prev" href="motivation.html" title="Motivation">
|
||||
<link rel="prev" href="discussion.html" title="Discussion">
|
||||
<link rel="next" href="synopsis.html" title="Synopsis">
|
||||
</head>
|
||||
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
|
||||
@ -20,7 +20,7 @@
|
||||
</tr></table>
|
||||
<hr>
|
||||
<div class="spirit-nav">
|
||||
<a accesskey="p" href="motivation.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="synopsis.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
|
||||
<a accesskey="p" href="discussion.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="synopsis.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
|
||||
</div>
|
||||
<div class="section">
|
||||
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
|
||||
@ -39,12 +39,12 @@
|
||||
In C++, we can <span class="emphasis"><em>declare</em></span> an object (a variable) of type
|
||||
<code class="computeroutput"><span class="identifier">T</span></code>, and we can give this variable
|
||||
an <span class="emphasis"><em>initial value</em></span> (through an <span class="emphasis"><em>initializer</em></span>.
|
||||
(c.f. 8.5)). When a declaration includes a non-empty initializer (an initial
|
||||
(cf. 8.5)). When a declaration includes a non-empty initializer (an initial
|
||||
value is given), it is said that the object has been initialized. If the
|
||||
declaration uses an empty initializer (no initial value is given), and neither
|
||||
default nor value initialization applies, it is said that the object is
|
||||
<span class="bold"><strong>uninitialized</strong></span>. Its actual value exist but
|
||||
has an <span class="emphasis"><em>indeterminate initial value</em></span> (c.f. 8.5.9). <code class="computeroutput"><span class="identifier">optional</span><span class="special"><</span><span class="identifier">T</span><span class="special">></span></code> intends
|
||||
has an <span class="emphasis"><em>indeterminate initial value</em></span> (cf. 8.5/11). <code class="computeroutput"><span class="identifier">optional</span><span class="special"><</span><span class="identifier">T</span><span class="special">></span></code> intends
|
||||
to formalize the notion of initialization (or lack of it) allowing a program
|
||||
to test whether an object has been initialized and stating that access to
|
||||
the value of an uninitialized object is undefined behavior. That is, when
|
||||
@ -67,13 +67,12 @@
|
||||
special value: <code class="computeroutput"><span class="identifier">EOF</span></code>, <code class="computeroutput"><span class="identifier">npos</span></code>, -1, etc... This is equivalent to
|
||||
adding the special value to the set of possible values of a given type. This
|
||||
super set of <code class="computeroutput"><span class="identifier">T</span></code> plus some
|
||||
<span class="emphasis"><em>nil_t</em></span>—were <code class="computeroutput"><span class="identifier">nil_t</span></code>
|
||||
is some stateless POD-can be modeled in modern languages as a <span class="bold"><strong>discriminated
|
||||
union</strong></span> of T and nil_t. Discriminated unions are often called <span class="emphasis"><em>variants</em></span>.
|
||||
A variant has a <span class="emphasis"><em>current type</em></span>, which in our case is either
|
||||
<code class="computeroutput"><span class="identifier">T</span></code> or <code class="computeroutput"><span class="identifier">nil_t</span></code>.
|
||||
Using the <a href="../../../../variant/index.html" target="_top">Boost.Variant</a>
|
||||
library, this model can be implemented in terms of <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">variant</span><span class="special"><</span><span class="identifier">T</span><span class="special">,</span><span class="identifier">nil_t</span><span class="special">></span></code>.
|
||||
<span class="emphasis"><em>nil_t</em></span>—where <code class="computeroutput"><span class="identifier">nil_t</span></code>
|
||||
is some stateless POD—can be modeled in modern languages as a <span class="bold"><strong>discriminated union</strong></span> of T and nil_t. Discriminated
|
||||
unions are often called <span class="emphasis"><em>variants</em></span>. A variant has a <span class="emphasis"><em>current
|
||||
type</em></span>, which in our case is either <code class="computeroutput"><span class="identifier">T</span></code>
|
||||
or <code class="computeroutput"><span class="identifier">nil_t</span></code>. Using the <a href="../../../../variant/index.html" target="_top">Boost.Variant</a> library, this model
|
||||
can be implemented in terms of <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">variant</span><span class="special"><</span><span class="identifier">T</span><span class="special">,</span><span class="identifier">nil_t</span><span class="special">></span></code>.
|
||||
There is precedent for a discriminated union as a model for an optional value:
|
||||
the <a href="http://www.haskell.org/" target="_top">Haskell</a> <span class="bold"><strong>Maybe</strong></span>
|
||||
built-in type constructor. Thus, a discriminated union <code class="computeroutput"><span class="identifier">T</span><span class="special">+</span><span class="identifier">nil_t</span></code>
|
||||
@ -329,8 +328,8 @@
|
||||
Such a <span class="emphasis"><em>de facto</em></span> idiom for referring to optional objects
|
||||
can be formalized in the form of a concept: the <a href="../../../../utility/OptionalPointee.html" target="_top">OptionalPointee</a>
|
||||
concept. This concept captures the syntactic usage of operators <code class="computeroutput"><span class="special">*</span></code>, <code class="computeroutput"><span class="special">-></span></code>
|
||||
and conversion to <code class="computeroutput"><span class="keyword">bool</span></code> to convey
|
||||
the notion of optionality.
|
||||
and contextual conversion to <code class="computeroutput"><span class="keyword">bool</span></code>
|
||||
to convey the notion of optionality.
|
||||
</p>
|
||||
<p>
|
||||
However, pointers are good to <span class="underline">refer</span>
|
||||
@ -407,7 +406,7 @@
|
||||
</tr></table>
|
||||
<hr>
|
||||
<div class="spirit-nav">
|
||||
<a accesskey="p" href="motivation.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="synopsis.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
|
||||
<a accesskey="p" href="discussion.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="synopsis.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
128
doc/html/boost_optional/discussion.html
Normal file
128
doc/html/boost_optional/discussion.html
Normal file
@ -0,0 +1,128 @@
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
|
||||
<title>Discussion</title>
|
||||
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
|
||||
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
|
||||
<link rel="home" href="../index.html" title="Chapter 1. Boost.Optional">
|
||||
<link rel="up" href="../index.html" title="Chapter 1. Boost.Optional">
|
||||
<link rel="prev" href="tutorial.html" title="Tutorial">
|
||||
<link rel="next" href="development.html" title="Development">
|
||||
</head>
|
||||
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
|
||||
<table cellpadding="2" width="100%"><tr>
|
||||
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
|
||||
<td align="center"><a href="../../../../../index.html">Home</a></td>
|
||||
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
|
||||
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
|
||||
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
|
||||
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
|
||||
</tr></table>
|
||||
<hr>
|
||||
<div class="spirit-nav">
|
||||
<a accesskey="p" href="tutorial.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="development.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
|
||||
</div>
|
||||
<div class="section">
|
||||
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
|
||||
<a name="boost_optional.discussion"></a><a class="link" href="discussion.html" title="Discussion">Discussion</a>
|
||||
</h2></div></div></div>
|
||||
<p>
|
||||
Consider these functions which should return a value but which might not have
|
||||
a value to return:
|
||||
</p>
|
||||
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
|
||||
<li class="listitem">
|
||||
(A) <code class="computeroutput"><span class="keyword">double</span> <span class="identifier">sqrt</span><span class="special">(</span><span class="keyword">double</span> <span class="identifier">n</span> <span class="special">);</span></code>
|
||||
</li>
|
||||
<li class="listitem">
|
||||
(B) <code class="computeroutput"><span class="keyword">char</span> <span class="identifier">get_async_input</span><span class="special">();</span></code>
|
||||
</li>
|
||||
<li class="listitem">
|
||||
(C) <code class="computeroutput"><span class="identifier">point</span> <span class="identifier">polygon</span><span class="special">::</span><span class="identifier">get_any_point_effectively_inside</span><span class="special">();</span></code>
|
||||
</li>
|
||||
</ul></div>
|
||||
<p>
|
||||
There are different approaches to the issue of not having a value to return.
|
||||
</p>
|
||||
<p>
|
||||
A typical approach is to consider the existence of a valid return value as
|
||||
a postcondition, so that if the function cannot compute the value to return,
|
||||
it has either undefined behavior (and can use assert in a debug build) or uses
|
||||
a runtime check and throws an exception if the postcondition is violated. This
|
||||
is a reasonable choice for example, for function (A), because the lack of a
|
||||
proper return value is directly related to an invalid parameter (out of domain
|
||||
argument), so it is appropriate to require the callee to supply only parameters
|
||||
in a valid domain for execution to continue normally.
|
||||
</p>
|
||||
<p>
|
||||
However, function (B), because of its asynchronous nature, does not fail just
|
||||
because it can't find a value to return; so it is incorrect to consider such
|
||||
a situation an error and assert or throw an exception. This function must return,
|
||||
and somehow, must tell the callee that it is not returning a meaningful value.
|
||||
</p>
|
||||
<p>
|
||||
A similar situation occurs with function (C): it is conceptually an error to
|
||||
ask a <span class="emphasis"><em>null-area</em></span> polygon to return a point inside itself,
|
||||
but in many applications, it is just impractical for performance reasons to
|
||||
treat this as an error (because detecting that the polygon has no area might
|
||||
be too expensive to be required to be tested previously), and either an arbitrary
|
||||
point (typically at infinity) is returned, or some efficient way to tell the
|
||||
callee that there is no such point is used.
|
||||
</p>
|
||||
<p>
|
||||
There are various mechanisms to let functions communicate that the returned
|
||||
value is not valid. One such mechanism, which is quite common since it has
|
||||
zero or negligible overhead, is to use a special value which is reserved to
|
||||
communicate this. Classical examples of such special values are <code class="computeroutput"><span class="identifier">EOF</span></code>, <code class="computeroutput"><span class="identifier">string</span><span class="special">::</span><span class="identifier">npos</span></code>, points
|
||||
at infinity, etc...
|
||||
</p>
|
||||
<p>
|
||||
When those values exist, i.e. the return type can hold all meaningful values
|
||||
<span class="emphasis"><em>plus</em></span> the <span class="emphasis"><em>signal</em></span> value, this mechanism
|
||||
is quite appropriate and well known. Unfortunately, there are cases when such
|
||||
values do not exist. In these cases, the usual alternative is either to use
|
||||
a wider type, such as <code class="computeroutput"><span class="keyword">int</span></code> in place
|
||||
of <code class="computeroutput"><span class="keyword">char</span></code>; or a compound type, such
|
||||
as <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span><span class="identifier">point</span><span class="special">,</span><span class="keyword">bool</span><span class="special">></span></code>.
|
||||
</p>
|
||||
<p>
|
||||
Returning a <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span><span class="identifier">T</span><span class="special">,</span><span class="keyword">bool</span><span class="special">></span></code>, thus attaching a boolean flag to the result
|
||||
which indicates if the result is meaningful, has the advantage that can be
|
||||
turned into a consistent idiom since the first element of the pair can be whatever
|
||||
the function would conceptually return. For example, the last two functions
|
||||
could have the following interface:
|
||||
</p>
|
||||
<pre class="programlisting"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span><span class="keyword">char</span><span class="special">,</span><span class="keyword">bool</span><span class="special">></span> <span class="identifier">get_async_input</span><span class="special">();</span>
|
||||
<span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span><span class="identifier">point</span><span class="special">,</span><span class="keyword">bool</span><span class="special">></span> <span class="identifier">polygon</span><span class="special">::</span><span class="identifier">get_any_point_effectively_inside</span><span class="special">();</span>
|
||||
</pre>
|
||||
<p>
|
||||
These functions use a consistent interface for dealing with possibly nonexistent
|
||||
results:
|
||||
</p>
|
||||
<pre class="programlisting"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span><span class="identifier">point</span><span class="special">,</span><span class="keyword">bool</span><span class="special">></span> <span class="identifier">p</span> <span class="special">=</span> <span class="identifier">poly</span><span class="special">.</span><span class="identifier">get_any_point_effectively_inside</span><span class="special">();</span>
|
||||
<span class="keyword">if</span> <span class="special">(</span> <span class="identifier">p</span><span class="special">.</span><span class="identifier">second</span> <span class="special">)</span>
|
||||
<span class="identifier">flood_fill</span><span class="special">(</span><span class="identifier">p</span><span class="special">.</span><span class="identifier">first</span><span class="special">);</span>
|
||||
</pre>
|
||||
<p>
|
||||
However, not only is this quite a burden syntactically, it is also error prone
|
||||
since the user can easily use the function result (first element of the pair)
|
||||
without ever checking if it has a valid value.
|
||||
</p>
|
||||
<p>
|
||||
Clearly, we need a better idiom.
|
||||
</p>
|
||||
</div>
|
||||
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
|
||||
<td align="left"></td>
|
||||
<td align="right"><div class="copyright-footer">Copyright © 2003-2007 Fernando Luis Cacciola Carballal<br>Copyright © 2014 Andrzej Krzemieński<p>
|
||||
Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
|
||||
</p>
|
||||
</div></td>
|
||||
</tr></table>
|
||||
<hr>
|
||||
<div class="spirit-nav">
|
||||
<a accesskey="p" href="tutorial.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="development.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -118,6 +118,13 @@
|
||||
This also applies to move assignments/constructors. However, move operations
|
||||
are made no-throw more often.
|
||||
</p>
|
||||
<p>
|
||||
Operation <code class="computeroutput"><span class="identifier">emplace</span></code> provides
|
||||
basic exception safety guarantee. If it throws, the optional object becomes
|
||||
uninitialized regardless of its initial state, and its previous contained value
|
||||
(if any) is destroyed. It doesn't call any assignment or move/copy constructor
|
||||
on <code class="computeroutput"><span class="identifier">T</span></code>.
|
||||
</p>
|
||||
<h4>
|
||||
<a name="boost_optional.exception_safety_guarantees.h0"></a>
|
||||
<span class="phrase"><a name="boost_optional.exception_safety_guarantees.swap"></a></span><a class="link" href="exception_safety_guarantees.html#boost_optional.exception_safety_guarantees.swap">Swap</a>
|
||||
|
@ -74,6 +74,8 @@
|
||||
|
||||
<span class="keyword">template</span><span class="special"><</span><span class="keyword">class</span> <span class="identifier">U</span><span class="special">></span> <span class="identifier">optional</span><span class="special">&</span> <span class="keyword">operator</span> <span class="special">=</span> <span class="special">(</span> <span class="identifier">optional</span><span class="special"><</span><span class="identifier">U</span><span class="special">>&&</span> <span class="identifier">rhs</span> <span class="special">)</span> <span class="special">;</span> <a class="link" href="detailed_semantics.html#reference_optional_operator_move_equal_other_optional"><span class="inlinemediaobject"><img src="../images/callouts/R.png" alt="R"></span></a>
|
||||
|
||||
<span class="keyword">template</span><span class="special"><</span><span class="keyword">class</span><span class="special">...</span> <span class="identifier">Args</span><span class="special">></span> <span class="keyword">void</span> <span class="identifier">emplace</span> <span class="special">(</span> <span class="identifier">Args</span><span class="special">...&&</span> <span class="identifier">args</span> <span class="special">)</span> <span class="special">;</span> <a class="link" href="detailed_semantics.html#reference_optional_emplace"><span class="inlinemediaobject"><img src="../images/callouts/R.png" alt="R"></span></a>
|
||||
|
||||
<span class="keyword">template</span><span class="special"><</span><span class="keyword">class</span> <span class="identifier">InPlaceFactory</span><span class="special">></span> <span class="identifier">optional</span><span class="special">&</span> <span class="keyword">operator</span> <span class="special">=</span> <span class="special">(</span> <span class="identifier">InPlaceFactory</span> <span class="keyword">const</span><span class="special">&</span> <span class="identifier">f</span> <span class="special">)</span> <span class="special">;</span> <a class="link" href="detailed_semantics.html#reference_optional_operator_equal_factory"><span class="inlinemediaobject"><img src="../images/callouts/R.png" alt="R"></span></a>
|
||||
|
||||
<span class="keyword">template</span><span class="special"><</span><span class="keyword">class</span> <span class="identifier">TypedInPlaceFactory</span><span class="special">></span> <span class="identifier">optional</span><span class="special">&</span> <span class="keyword">operator</span> <span class="special">=</span> <span class="special">(</span> <span class="identifier">TypedInPlaceFactory</span> <span class="keyword">const</span><span class="special">&</span> <span class="identifier">f</span> <span class="special">)</span> <span class="special">;</span> <a class="link" href="detailed_semantics.html#reference_optional_operator_equal_factory"><span class="inlinemediaobject"><img src="../images/callouts/R.png" alt="R"></span></a>
|
||||
|
239
doc/html/boost_optional/tutorial.html
Normal file
239
doc/html/boost_optional/tutorial.html
Normal file
@ -0,0 +1,239 @@
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
|
||||
<title>Tutorial</title>
|
||||
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
|
||||
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
|
||||
<link rel="home" href="../index.html" title="Chapter 1. Boost.Optional">
|
||||
<link rel="up" href="../index.html" title="Chapter 1. Boost.Optional">
|
||||
<link rel="prev" href="../index.html" title="Chapter 1. Boost.Optional">
|
||||
<link rel="next" href="discussion.html" title="Discussion">
|
||||
</head>
|
||||
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
|
||||
<table cellpadding="2" width="100%"><tr>
|
||||
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
|
||||
<td align="center"><a href="../../../../../index.html">Home</a></td>
|
||||
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
|
||||
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
|
||||
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
|
||||
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
|
||||
</tr></table>
|
||||
<hr>
|
||||
<div class="spirit-nav">
|
||||
<a accesskey="p" href="../index.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="discussion.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
|
||||
</div>
|
||||
<div class="section">
|
||||
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
|
||||
<a name="boost_optional.tutorial"></a><a class="link" href="tutorial.html" title="Tutorial">Tutorial</a>
|
||||
</h2></div></div></div>
|
||||
<div class="toc"><dl class="toc">
|
||||
<dt><span class="section"><a href="tutorial.html#boost_optional.tutorial.optional_return_values">Optional
|
||||
return values</a></span></dt>
|
||||
<dt><span class="section"><a href="tutorial.html#boost_optional.tutorial.optional_data_members">Optional
|
||||
data members</a></span></dt>
|
||||
<dt><span class="section"><a href="tutorial.html#boost_optional.tutorial.bypassing_unnecessary_default_construction">Bypassing
|
||||
unnecessary default construction</a></span></dt>
|
||||
</dl></div>
|
||||
<div class="section">
|
||||
<div class="titlepage"><div><div><h3 class="title">
|
||||
<a name="boost_optional.tutorial.optional_return_values"></a><a class="link" href="tutorial.html#boost_optional.tutorial.optional_return_values" title="Optional return values">Optional
|
||||
return values</a>
|
||||
</h3></div></div></div>
|
||||
<p>
|
||||
Let's write and use a converter function that converts an a <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span></code>
|
||||
to an <code class="computeroutput"><span class="keyword">int</span></code>. It is possible that
|
||||
for a given string (e.g. <code class="computeroutput"><span class="string">"cat"</span></code>)
|
||||
there exist no value of type <code class="computeroutput"><span class="keyword">int</span></code>
|
||||
capable of representing the conversion result. We do not consider such situation
|
||||
an error. We expect that the converter can be used only to check if the conversion
|
||||
is possible. A natural signature for this function can be:
|
||||
</p>
|
||||
<pre class="programlisting"><span class="preprocessor">#include</span> <span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">optional</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span>
|
||||
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">optionl</span><span class="special"><</span><span class="keyword">int</span><span class="special">></span> <span class="identifier">convert</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span><span class="special">&</span> <span class="identifier">text</span><span class="special">);</span>
|
||||
</pre>
|
||||
<p>
|
||||
All necessary functionality can be included with one header <code class="computeroutput"><span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">optional</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span></code>.
|
||||
The above function signature means that the function can either return a
|
||||
value of type <code class="computeroutput"><span class="keyword">int</span></code> or a flag
|
||||
indicating that no value of <code class="computeroutput"><span class="keyword">int</span></code>
|
||||
is available. This does not indicate an error. It is like one additional
|
||||
value of <code class="computeroutput"><span class="keyword">int</span></code>. This is how we
|
||||
can use our function:
|
||||
</p>
|
||||
<pre class="programlisting"><span class="keyword">const</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span><span class="special">&</span> <span class="identifier">text</span> <span class="special">=</span> <span class="comment">/*... */</span><span class="special">;</span>
|
||||
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">optionl</span><span class="special"><</span><span class="keyword">int</span><span class="special">></span> <span class="identifier">oi</span> <span class="special">=</span> <span class="identifier">convert</span><span class="special">(</span><span class="identifier">text</span><span class="special">);</span> <span class="comment">// move-construct</span>
|
||||
<span class="keyword">if</span> <span class="special">(</span><span class="identifier">oi</span><span class="special">)</span> <span class="comment">// contextual conversion to bool</span>
|
||||
<span class="keyword">int</span> <span class="identifier">i</span> <span class="special">=</span> <span class="special">*</span><span class="identifier">oi</span><span class="special">;</span> <span class="comment">// operator*</span>
|
||||
</pre>
|
||||
<p>
|
||||
In order to test if <code class="computeroutput"><span class="identifier">optional</span></code>
|
||||
contains a value, we use the contextual conversion to type <code class="computeroutput"><span class="keyword">bool</span></code>. Because of this we can combine the initialization
|
||||
of the optional object and the test into one instruction:
|
||||
</p>
|
||||
<pre class="programlisting"><span class="keyword">if</span> <span class="special">(</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">optionl</span><span class="special"><</span><span class="keyword">int</span><span class="special">></span> <span class="identifier">oi</span> <span class="special">=</span> <span class="identifier">convert</span><span class="special">(</span><span class="identifier">text</span><span class="special">))</span>
|
||||
<span class="keyword">int</span> <span class="identifier">i</span> <span class="special">=</span> <span class="special">*</span><span class="identifier">oi</span><span class="special">;</span>
|
||||
</pre>
|
||||
<p>
|
||||
We extract the contained value with <code class="computeroutput"><span class="keyword">operator</span><span class="special">*</span></code> (and with <code class="computeroutput"><span class="keyword">operator</span><span class="special">-></span></code> where it makes sense). An attempt to
|
||||
extract the contained value of an uninitialized optional object is an <span class="emphasis"><em>undefined
|
||||
behaviour</em></span> (UB). This implementation guards the call with <code class="computeroutput"><span class="identifier">BOOST_ASSERT</span></code>. Therefore you should be sure
|
||||
that the contained value is there before extracting. For instance, the following
|
||||
code is reasonably UB-safe:
|
||||
</p>
|
||||
<pre class="programlisting"><span class="keyword">int</span> <span class="identifier">i</span> <span class="special">=</span> <span class="special">*</span><span class="identifier">convert</span><span class="special">(</span><span class="string">"100"</span><span class="special">);</span>
|
||||
</pre>
|
||||
<p>
|
||||
This is because we know that string value <code class="computeroutput"><span class="string">"100"</span></code>
|
||||
converts to a valid value of <code class="computeroutput"><span class="keyword">int</span></code>.
|
||||
If you do not like this potential UB, you can use an alternative way of extracting
|
||||
the contained value:
|
||||
</p>
|
||||
<pre class="programlisting"><span class="keyword">try</span> <span class="special">{</span>
|
||||
<span class="keyword">int</span> <span class="identifier">j</span> <span class="special">=</span> <span class="identifier">convert</span><span class="special">(</span><span class="identifier">text</span><span class="special">).</span><span class="identifier">value</span><span class="special">();</span>
|
||||
<span class="special">}</span>
|
||||
<span class="keyword">catch</span> <span class="special">(</span><span class="keyword">const</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">bad_optional_access</span><span class="special">&)</span> <span class="special">{</span>
|
||||
<span class="comment">// deal with it</span>
|
||||
<span class="special">}</span>
|
||||
</pre>
|
||||
<p>
|
||||
This version throws an exception upon an attempt to access a non-existent
|
||||
contained value. If your way of dealing with the missing value is to use
|
||||
some default, like <code class="computeroutput"><span class="number">0</span></code>, there exists
|
||||
a yet another alternative:
|
||||
</p>
|
||||
<pre class="programlisting"><span class="keyword">int</span> <span class="identifier">k</span> <span class="special">=</span> <span class="identifier">convert</span><span class="special">(</span><span class="identifier">text</span><span class="special">).</span><span class="identifier">value_or</span><span class="special">(</span><span class="number">0</span><span class="special">);</span>
|
||||
</pre>
|
||||
<p>
|
||||
This uses the <code class="computeroutput"><span class="identifier">atoi</span></code>-like approach
|
||||
to conversions: if <code class="computeroutput"><span class="identifier">text</span></code> does
|
||||
not represent an integral number just return <code class="computeroutput"><span class="number">0</span></code>.
|
||||
Now, let's consider how function <code class="computeroutput"><span class="identifier">convert</span></code>
|
||||
can be implemented.
|
||||
</p>
|
||||
<pre class="programlisting"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">optionl</span><span class="special"><</span><span class="keyword">int</span><span class="special">></span> <span class="identifier">convert</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span><span class="special">&</span> <span class="identifier">text</span><span class="special">)</span>
|
||||
<span class="special">{</span>
|
||||
<span class="identifier">std</span><span class="special">::</span><span class="identifier">stringstream</span> <span class="identifier">s</span><span class="special">(</span><span class="identifier">text</span><span class="special">);</span>
|
||||
<span class="keyword">int</span> <span class="identifier">i</span><span class="special">;</span>
|
||||
<span class="keyword">if</span> <span class="special">((</span><span class="identifier">s</span> <span class="special">>></span> <span class="identifier">i</span><span class="special">)</span> <span class="special">&&</span> <span class="identifier">s</span><span class="special">.</span><span class="identifier">get</span><span class="special">()</span> <span class="special">==</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">char_traits</span><span class="special"><</span><span class="keyword">char</span><span class="special">>::</span><span class="identifier">eof</span><span class="special">())</span>
|
||||
<span class="keyword">return</span> <span class="identifier">i</span><span class="special">;</span>
|
||||
<span class="keyword">else</span>
|
||||
<span class="keyword">return</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">none</span><span class="special">;</span>
|
||||
<span class="special">}</span>
|
||||
</pre>
|
||||
<p>
|
||||
Observe the two return statements. <code class="computeroutput"><span class="keyword">return</span>
|
||||
<span class="identifier">i</span></code> uses the converting constructor
|
||||
that can create <code class="computeroutput"><span class="identifier">optional</span><span class="special"><</span><span class="identifier">T</span><span class="special">></span></code>
|
||||
from <code class="computeroutput"><span class="identifier">T</span></code>. Thus constructed
|
||||
optional object is initialized and its value is a copy of <code class="computeroutput"><span class="identifier">i</span></code>.
|
||||
The other return statement uses another converting constructor from a special
|
||||
tag <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">none</span></code>. It is used to indicate that we want
|
||||
to create an uninitialized optional object.
|
||||
</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<div class="titlepage"><div><div><h3 class="title">
|
||||
<a name="boost_optional.tutorial.optional_data_members"></a><a class="link" href="tutorial.html#boost_optional.tutorial.optional_data_members" title="Optional data members">Optional
|
||||
data members</a>
|
||||
</h3></div></div></div>
|
||||
<p>
|
||||
Suppose we want to implement a <span class="emphasis"><em>lazy load</em></span> optimization.
|
||||
This is because we do not want to perform an expensive initialization of
|
||||
our <code class="computeroutput"><span class="identifier">Resource</span></code> until (if at
|
||||
all) it is really used. We can do it this way:
|
||||
</p>
|
||||
<pre class="programlisting"><span class="keyword">class</span> <span class="identifier">Widget</span>
|
||||
<span class="special">{</span>
|
||||
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">optional</span><span class="special"><</span><span class="identifier">Resource</span><span class="special">></span> <span class="identifier">resource_</span><span class="special">;</span>
|
||||
|
||||
<span class="keyword">public</span><span class="special">:</span>
|
||||
<span class="identifier">Widget</span><span class="special">()</span> <span class="special">{}</span>
|
||||
|
||||
<span class="identifier">Resource</span><span class="special">&</span> <span class="identifier">getResource</span><span class="special">()</span> <span class="comment">// not thread-safe</span>
|
||||
<span class="special">{</span>
|
||||
<span class="keyword">if</span> <span class="special">(</span><span class="identifier">resource_</span> <span class="special">==</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">none</span><span class="special">)</span>
|
||||
<span class="identifier">resource_</span><span class="special">.</span><span class="identifier">emplace</span><span class="special">(</span><span class="string">"resource"</span><span class="special">,</span> <span class="string">"arguments"</span><span class="special">);</span>
|
||||
|
||||
<span class="keyword">return</span> <span class="special">*</span><span class="identifier">resource_</span><span class="special">;</span>
|
||||
<span class="special">}</span>
|
||||
<span class="special">};</span>
|
||||
</pre>
|
||||
<p>
|
||||
<code class="computeroutput"><span class="identifier">optional</span></code>'s default constructor
|
||||
creates an uninitialized optional. No call to <code class="computeroutput"><span class="identifier">Resource</span></code>'s
|
||||
default constructor is attempted. <code class="computeroutput"><span class="identifier">Resource</span></code>
|
||||
doesn't have to be <a href="http://www.sgi.com/tech/stl/DefaultConstructible.html" target="_top">Default
|
||||
Constructible</a>. In function <code class="computeroutput"><span class="identifier">getResource</span></code>
|
||||
we first check if <code class="computeroutput"><span class="identifier">resource_</span></code>
|
||||
is initialized. This time we do not use the contextual conversion to <code class="computeroutput"><span class="keyword">bool</span></code>, but a comparison with <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">none</span></code>. These two ways are equivalent. Function
|
||||
<code class="computeroutput"><span class="identifier">emplace</span></code> initializes the optional
|
||||
in-place by perfect-forwarding the arguments to the constructor of <code class="computeroutput"><span class="identifier">Resource</span></code>. No copy- or move-construction
|
||||
is involved here. <code class="computeroutput"><span class="identifier">Resource</span></code>
|
||||
doesn't even have to be <code class="computeroutput"><span class="identifier">MoveConstructible</span></code>.
|
||||
</p>
|
||||
<div class="note"><table border="0" summary="Note">
|
||||
<tr>
|
||||
<td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="../../../../../doc/src/images/note.png"></td>
|
||||
<th align="left">Note</th>
|
||||
</tr>
|
||||
<tr><td align="left" valign="top"><p>
|
||||
Function <code class="computeroutput"><span class="identifier">emplace</span></code> is only
|
||||
available on compilers that support rvalue references and variadic templates.
|
||||
If your compiler does not support these features and you still need to
|
||||
avoid any move-constructions, use <a class="link" href="in_place_factories.html" title="In-Place Factories">In-Place
|
||||
Factories</a>.
|
||||
</p></td></tr>
|
||||
</table></div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<div class="titlepage"><div><div><h3 class="title">
|
||||
<a name="boost_optional.tutorial.bypassing_unnecessary_default_construction"></a><a class="link" href="tutorial.html#boost_optional.tutorial.bypassing_unnecessary_default_construction" title="Bypassing unnecessary default construction">Bypassing
|
||||
unnecessary default construction</a>
|
||||
</h3></div></div></div>
|
||||
<p>
|
||||
Suppose we have class <code class="computeroutput"><span class="identifier">Date</span></code>,
|
||||
which does not have a default constructor: there is no good candidate for
|
||||
a default date. We have a function that returns two dates in form of a <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">tuple</span></code>:
|
||||
</p>
|
||||
<pre class="programlisting"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">tuple</span><span class="special"><</span><span class="identifier">Date</span><span class="special">,</span> <span class="identifier">Date</span><span class="special">></span> <span class="identifier">getPeriod</span><span class="special">();</span>
|
||||
</pre>
|
||||
<p>
|
||||
In other place we want to use the result of <code class="computeroutput"><span class="identifier">getPeriod</span></code>,
|
||||
but want the two dates to be named: <code class="computeroutput"><span class="identifier">begin</span></code>
|
||||
and <code class="computeroutput"><span class="identifier">end</span></code>. We want to implement
|
||||
something like 'multiple return values':
|
||||
</p>
|
||||
<pre class="programlisting"><span class="identifier">Date</span> <span class="identifier">begin</span><span class="special">,</span> <span class="identifier">end</span><span class="special">;</span> <span class="comment">// Error: no default ctor!</span>
|
||||
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">tie</span><span class="special">(</span><span class="identifier">begin</span><span class="special">,</span> <span class="identifier">end</span><span class="special">)</span> <span class="special">=</span> <span class="identifier">getPeriod</span><span class="special">();</span>
|
||||
</pre>
|
||||
<p>
|
||||
The second line works already, this is the capability of Boost.Tuple library,
|
||||
but the first line won't work. We could set some initial invented dates,
|
||||
but it is confusing and may be an unacceptable cost, given that these values
|
||||
will be overwritten in the next line anyway. This is where <code class="computeroutput"><span class="identifier">optional</span></code> can help:
|
||||
</p>
|
||||
<pre class="programlisting"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">optional</span><span class="special"><</span><span class="identifier">Date</span><span class="special">></span> <span class="identifier">begin</span><span class="special">,</span> <span class="identifier">end</span><span class="special">;</span>
|
||||
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">tie</span><span class="special">(</span><span class="identifier">begin</span><span class="special">,</span> <span class="identifier">end</span><span class="special">)</span> <span class="special">=</span> <span class="identifier">getPeriod</span><span class="special">();</span>
|
||||
</pre>
|
||||
<p>
|
||||
It works because inside <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">tie</span></code> a
|
||||
move-assignment from <code class="computeroutput"><span class="identifier">T</span></code> is
|
||||
invoked on <code class="computeroutput"><span class="identifier">optional</span><span class="special"><</span><span class="identifier">T</span><span class="special">></span></code>,
|
||||
which internally calls a move-constructor of <code class="computeroutput"><span class="identifier">T</span></code>.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
|
||||
<td align="left"></td>
|
||||
<td align="right"><div class="copyright-footer">Copyright © 2003-2007 Fernando Luis Cacciola Carballal<br>Copyright © 2014 Andrzej Krzemieński<p>
|
||||
Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
|
||||
</p>
|
||||
</div></td>
|
||||
</tr></table>
|
||||
<hr>
|
||||
<div class="spirit-nav">
|
||||
<a accesskey="p" href="../index.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="discussion.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
@ -27,9 +27,17 @@
|
||||
<a name="boost_optional.type_requirements"></a><a class="link" href="type_requirements.html" title="Type requirements">Type requirements</a>
|
||||
</h2></div></div></div>
|
||||
<p>
|
||||
In general, <code class="computeroutput"><span class="identifier">T</span></code> must be <code class="computeroutput"><span class="identifier">MoveConstructible</span></code> and have a no-throw destructor.
|
||||
The <code class="computeroutput"><span class="identifier">MoveConstructible</span></code> requirement
|
||||
is not needed if <span class="bold"><strong>InPlaceFactories</strong></span> are used.
|
||||
At the very minimum for <code class="computeroutput"><span class="identifier">optional</span><span class="special"><</span><span class="identifier">T</span><span class="special">></span></code>
|
||||
to work with a minimum interface it is required that <code class="computeroutput"><span class="identifier">T</span></code>
|
||||
has a publicly accessible no-throw destructor. In that case you need to initialize
|
||||
the optional object with function <code class="computeroutput"><span class="identifier">emplace</span><span class="special">()</span></code> or use <span class="bold"><strong>InPlaceFactories</strong></span>.
|
||||
Additionally, if <code class="computeroutput"><span class="identifier">T</span></code> is <code class="computeroutput"><span class="identifier">Moveable</span></code>, <code class="computeroutput"><span class="identifier">optional</span><span class="special"><</span><span class="identifier">T</span><span class="special">></span></code>
|
||||
is also <code class="computeroutput"><span class="identifier">Moveable</span></code> and can be
|
||||
easily initialized from an rvalue of type <code class="computeroutput"><span class="identifier">T</span></code>
|
||||
and be passed by value. Additionally if <code class="computeroutput"><span class="identifier">T</span></code>
|
||||
is <code class="computeroutput"><span class="identifier">Copyable</span></code>, <code class="computeroutput"><span class="identifier">optional</span><span class="special"><</span><span class="identifier">T</span><span class="special">></span></code> is
|
||||
also <code class="computeroutput"><span class="identifier">Copyable</span></code> and can be easily
|
||||
initialized from an lvalue of type <code class="computeroutput"><span class="identifier">T</span></code>.
|
||||
</p>
|
||||
<p>
|
||||
<code class="computeroutput"><span class="identifier">T</span></code> <span class="underline">is
|
||||
|
@ -5,7 +5,7 @@
|
||||
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
|
||||
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
|
||||
<link rel="home" href="index.html" title="Chapter 1. Boost.Optional">
|
||||
<link rel="next" href="boost_optional/motivation.html" title="Motivation">
|
||||
<link rel="next" href="boost_optional/tutorial.html" title="Tutorial">
|
||||
</head>
|
||||
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
|
||||
<table cellpadding="2" width="100%"><tr>
|
||||
@ -17,7 +17,7 @@
|
||||
<td align="center"><a href="../../../../more/index.htm">More</a></td>
|
||||
</tr></table>
|
||||
<hr>
|
||||
<div class="spirit-nav"><a accesskey="n" href="boost_optional/motivation.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a></div>
|
||||
<div class="spirit-nav"><a accesskey="n" href="boost_optional/tutorial.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a></div>
|
||||
<div class="chapter">
|
||||
<div class="titlepage"><div>
|
||||
<div><h2 class="title">
|
||||
@ -38,7 +38,20 @@
|
||||
<p><b>Table of Contents</b></p>
|
||||
<dl class="toc">
|
||||
<dt><span class="section"><a href="index.html#optional.introduction">Introduction</a></span></dt>
|
||||
<dt><span class="section"><a href="boost_optional/motivation.html">Motivation</a></span></dt>
|
||||
<dd><dl>
|
||||
<dt><span class="section"><a href="index.html#optional.introduction.problem">Problem</a></span></dt>
|
||||
<dt><span class="section"><a href="index.html#optional.introduction.solution">Solution</a></span></dt>
|
||||
</dl></dd>
|
||||
<dt><span class="section"><a href="boost_optional/tutorial.html">Tutorial</a></span></dt>
|
||||
<dd><dl>
|
||||
<dt><span class="section"><a href="boost_optional/tutorial.html#boost_optional.tutorial.optional_return_values">Optional
|
||||
return values</a></span></dt>
|
||||
<dt><span class="section"><a href="boost_optional/tutorial.html#boost_optional.tutorial.optional_data_members">Optional
|
||||
data members</a></span></dt>
|
||||
<dt><span class="section"><a href="boost_optional/tutorial.html#boost_optional.tutorial.bypassing_unnecessary_default_construction">Bypassing
|
||||
unnecessary default construction</a></span></dt>
|
||||
</dl></dd>
|
||||
<dt><span class="section"><a href="boost_optional/discussion.html">Discussion</a></span></dt>
|
||||
<dt><span class="section"><a href="boost_optional/development.html">Development</a></span></dt>
|
||||
<dd><dl>
|
||||
<dt><span class="section"><a href="boost_optional/development.html#boost_optional.development.the_models">The models</a></span></dt>
|
||||
@ -78,24 +91,60 @@
|
||||
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
|
||||
<a name="optional.introduction"></a><a class="link" href="index.html#optional.introduction" title="Introduction">Introduction</a>
|
||||
</h2></div></div></div>
|
||||
<div class="toc"><dl class="toc">
|
||||
<dt><span class="section"><a href="index.html#optional.introduction.problem">Problem</a></span></dt>
|
||||
<dt><span class="section"><a href="index.html#optional.introduction.solution">Solution</a></span></dt>
|
||||
</dl></div>
|
||||
<p>
|
||||
This library can be used to represent 'optional' (or 'nullable') objects that
|
||||
can be safely passed by value:
|
||||
Class template <code class="computeroutput"><span class="identifier">optional</span></code> is
|
||||
a wrapper for representing 'optional' (or 'nullable') objects who may not (yet)
|
||||
contain a valid value. Optional objects offer full value semantics; they are
|
||||
good for passing by value and usage inside STL containers. This is a header-only
|
||||
library.
|
||||
</p>
|
||||
<pre class="programlisting"><span class="identifier">optional</span><span class="special"><</span><span class="keyword">int</span><span class="special">></span> <span class="identifier">readInt</span><span class="special">();</span> <span class="comment">// this function may return either an int or a not-an-int</span>
|
||||
<div class="section">
|
||||
<div class="titlepage"><div><div><h3 class="title">
|
||||
<a name="optional.introduction.problem"></a><a class="link" href="index.html#optional.introduction.problem" title="Problem">Problem</a>
|
||||
</h3></div></div></div>
|
||||
<p>
|
||||
Suppose we want to read a parameter form a config file which represents some
|
||||
integral value, let's call it <code class="computeroutput"><span class="string">"MaxValue"</span></code>.
|
||||
It is possible that this parameter is not specified; such situation is no
|
||||
error. It is valid to not specify the parameter and in that case the program
|
||||
is supposed to behave slightly different. Also suppose that any possible
|
||||
value of type <code class="computeroutput"><span class="keyword">int</span></code> is a valid
|
||||
value for <code class="computeroutput"><span class="string">"MaxValue"</span></code>,
|
||||
so we cannot jut use <code class="computeroutput"><span class="special">-</span><span class="number">1</span></code>
|
||||
to represent the absence of the parameter in the config file.
|
||||
</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<div class="titlepage"><div><div><h3 class="title">
|
||||
<a name="optional.introduction.solution"></a><a class="link" href="index.html#optional.introduction.solution" title="Solution">Solution</a>
|
||||
</h3></div></div></div>
|
||||
<p>
|
||||
This is how you solve it with <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">optional</span></code>:
|
||||
</p>
|
||||
<pre class="programlisting"><span class="preprocessor">#include</span> <span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">optional</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span>
|
||||
|
||||
<span class="keyword">if</span> <span class="special">(</span><span class="identifier">optional</span><span class="special"><</span><span class="keyword">int</span><span class="special">></span> <span class="identifier">oi</span> <span class="special">=</span> <span class="identifier">readInt</span><span class="special">())</span> <span class="comment">// did I get a real int</span>
|
||||
<span class="identifier">cout</span> <span class="special"><<</span> <span class="string">"my int is: "</span> <span class="special"><<</span> <span class="special">*</span><span class="identifier">oi</span><span class="special">;</span> <span class="comment">// use my int</span>
|
||||
<span class="keyword">else</span>
|
||||
<span class="identifier">cout</span> <span class="special"><<</span> <span class="string">"I have no int"</span><span class="special">;</span>
|
||||
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">optional</span><span class="special"><</span><span class="keyword">int</span><span class="special">></span> <span class="identifier">getConfigParam</span><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span> <span class="identifier">name</span><span class="special">);</span> <span class="comment">// return either an int or a `not-an-int`</span>
|
||||
|
||||
<span class="keyword">int</span> <span class="identifier">main</span><span class="special">()</span>
|
||||
<span class="special">{</span>
|
||||
<span class="keyword">if</span> <span class="special">(</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">optional</span><span class="special"><</span><span class="keyword">int</span><span class="special">></span> <span class="identifier">oi</span> <span class="special">=</span> <span class="identifier">getConfigParam</span><span class="special">(</span><span class="string">"MaxValue"</span><span class="special">))</span> <span class="comment">// did I get a real int?</span>
|
||||
<span class="identifier">runWithMax</span><span class="special">(*</span><span class="identifier">oi</span><span class="special">);</span> <span class="comment">// use my int</span>
|
||||
<span class="keyword">else</span>
|
||||
<span class="identifier">runWithNoMax</span><span class="special">();</span>
|
||||
<span class="special">}</span>
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
|
||||
<td align="left"><p><small>Last revised: May 23, 2014 at 14:35:08 GMT</small></p></td>
|
||||
<td align="left"><p><small>Last revised: June 03, 2014 at 14:35:30 GMT</small></p></td>
|
||||
<td align="right"><div class="copyright-footer"></div></td>
|
||||
</tr></table>
|
||||
<hr>
|
||||
<div class="spirit-nav"><a accesskey="n" href="boost_optional/motivation.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a></div>
|
||||
<div class="spirit-nav"><a accesskey="n" href="boost_optional/tutorial.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a></div>
|
||||
</body>
|
||||
</html>
|
||||
|
@ -1,28 +0,0 @@
|
||||
// Copyright (C) 2003, Fernando Luis Cacciola Carballal.
|
||||
//
|
||||
// Use, modification, and distribution is subject to the Boost Software
|
||||
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
// See http://www.boost.org/libs/optional for documentation.
|
||||
//
|
||||
// You are welcome to contact the author at:
|
||||
// fernando_cacciola@hotmail.com
|
||||
//
|
||||
#ifndef BOOST_DETAIL_NONE_T_17SEP2003_HPP
|
||||
#define BOOST_DETAIL_NONE_T_17SEP2003_HPP
|
||||
|
||||
namespace boost {
|
||||
|
||||
namespace detail {
|
||||
|
||||
struct none_helper{};
|
||||
|
||||
typedef int none_helper::*none_t ;
|
||||
|
||||
} // namespace detail
|
||||
|
||||
} // namespace boost
|
||||
|
||||
#endif
|
||||
|
@ -460,14 +460,26 @@ class optional_base : public optional_tag
|
||||
|
||||
void construct ( argument_type val )
|
||||
{
|
||||
new (m_storage.address()) internal_type(val) ;
|
||||
::new (m_storage.address()) internal_type(val) ;
|
||||
m_initialized = true ;
|
||||
}
|
||||
|
||||
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
|
||||
void construct ( rval_reference_type val )
|
||||
{
|
||||
new (m_storage.address()) internal_type( types::move(val) ) ;
|
||||
::new (m_storage.address()) internal_type( types::move(val) ) ;
|
||||
m_initialized = true ;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if (!defined BOOST_NO_CXX11_RVALUE_REFERENCES) && (!defined BOOST_NO_CXX11_VARIADIC_TEMPLATES)
|
||||
// Constructs in-place
|
||||
// upon exception *this is always uninitialized
|
||||
template<class... Args>
|
||||
void emplace_assign ( Args&&... args )
|
||||
{
|
||||
destroy();
|
||||
::new (m_storage.address()) internal_type( boost::forward<Args>(args)... );
|
||||
m_initialized = true ;
|
||||
}
|
||||
#endif
|
||||
@ -507,6 +519,7 @@ class optional_base : public optional_tag
|
||||
destroy();
|
||||
construct(factory,tag);
|
||||
}
|
||||
|
||||
#else
|
||||
// Constructs in-place using the given factory
|
||||
template<class Expr>
|
||||
@ -908,6 +921,16 @@ class optional : public optional_detail::optional_base<T>
|
||||
return *this ;
|
||||
}
|
||||
|
||||
#if (!defined BOOST_NO_CXX11_RVALUE_REFERENCES) && (!defined BOOST_NO_CXX11_VARIADIC_TEMPLATES)
|
||||
// Constructs in-place
|
||||
// upon exception *this is always uninitialized
|
||||
template<class... Args>
|
||||
void emplace ( Args&&... args )
|
||||
{
|
||||
this->emplace_assign( boost::forward<Args>(args)... );
|
||||
}
|
||||
#endif
|
||||
|
||||
void swap( optional & arg )
|
||||
BOOST_NOEXCEPT_IF(::boost::is_nothrow_move_constructible<T>::value && ::boost::is_nothrow_move_assignable<T>::value)
|
||||
{
|
||||
|
@ -24,6 +24,7 @@ import testing ;
|
||||
[ run optional_test_move.cpp ]
|
||||
[ run optional_test_equals_none.cpp ]
|
||||
[ run optional_test_value_access.cpp ]
|
||||
[ run optional_test_emplace.cpp ]
|
||||
[ compile-fail optional_test_fail1.cpp ]
|
||||
[ compile-fail optional_test_fail3a.cpp ]
|
||||
[ compile-fail optional_test_fail3b.cpp ]
|
||||
|
169
test/optional_test_emplace.cpp
Normal file
169
test/optional_test_emplace.cpp
Normal file
@ -0,0 +1,169 @@
|
||||
// Copyright (C) 2014 Andrzej Krzemienski.
|
||||
//
|
||||
// Use, modification, and distribution is subject to the Boost Software
|
||||
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
|
||||
// http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
// See http://www.boost.org/lib/optional for documentation.
|
||||
//
|
||||
// You are welcome to contact the author at:
|
||||
// akrzemi1@gmail.com
|
||||
//
|
||||
// Revisions:
|
||||
//
|
||||
#include<iostream>
|
||||
#include<stdexcept>
|
||||
#include<string>
|
||||
|
||||
#define BOOST_ENABLE_ASSERT_HANDLER
|
||||
|
||||
#include "boost/bind/apply.hpp" // Included just to test proper interaction with boost::apply<> as reported by Daniel Wallin
|
||||
#include "boost/mpl/bool.hpp"
|
||||
#include "boost/mpl/bool_fwd.hpp" // For mpl::true_ and mpl::false_
|
||||
#include "boost/static_assert.hpp"
|
||||
|
||||
#include "boost/optional/optional.hpp"
|
||||
|
||||
#ifdef __BORLANDC__
|
||||
#pragma hdrstop
|
||||
#endif
|
||||
|
||||
#include "boost/none.hpp"
|
||||
|
||||
#include "boost/test/minimal.hpp"
|
||||
|
||||
#include "optional_test_common.cpp"
|
||||
|
||||
//#ifndef BOOST_OPTIONAL_NO_CONVERTING_ASSIGNMENT
|
||||
//#ifndef BOOST_OPTIONAL_NO_CONVERTING_COPY_CTOR
|
||||
|
||||
#if (!defined BOOST_NO_CXX11_RVALUE_REFERENCES) && (!defined BOOST_NO_CXX11_VARIADIC_TEMPLATES)
|
||||
|
||||
class Guard
|
||||
{
|
||||
public:
|
||||
int which_ctor;
|
||||
Guard () : which_ctor(0) { }
|
||||
Guard (int&, double&&) : which_ctor(1) { }
|
||||
Guard (int&&, double&) : which_ctor(2) { }
|
||||
Guard (int&&, double&&) : which_ctor(3) { }
|
||||
Guard (int&, double&) : which_ctor(4) { }
|
||||
Guard (std::string const&) : which_ctor(5) { }
|
||||
Guard (std::string &) : which_ctor(6) { }
|
||||
Guard (std::string &&) : which_ctor(7) { }
|
||||
private:
|
||||
Guard(Guard&&);
|
||||
Guard(Guard const&);
|
||||
void operator=(Guard &&);
|
||||
void operator=(Guard const&);
|
||||
};
|
||||
|
||||
struct Thrower
|
||||
{
|
||||
Thrower(bool throw_) { if (throw_) throw int(); }
|
||||
|
||||
private:
|
||||
Thrower(Thrower const&);
|
||||
Thrower(Thrower&&);
|
||||
};
|
||||
|
||||
struct ThrowOnMove
|
||||
{
|
||||
ThrowOnMove(ThrowOnMove&&) { throw int(); }
|
||||
ThrowOnMove(ThrowOnMove const&) { throw int(); }
|
||||
ThrowOnMove(int){}
|
||||
};
|
||||
|
||||
void test_emplace()
|
||||
{
|
||||
int i = 0;
|
||||
double d = 0.0;
|
||||
const std::string cs;
|
||||
std::string ms;
|
||||
optional<Guard> o;
|
||||
|
||||
o.emplace();
|
||||
BOOST_CHECK(o);
|
||||
BOOST_CHECK(0 == o->which_ctor);
|
||||
|
||||
o.emplace(i, 2.0);
|
||||
BOOST_CHECK(o);
|
||||
BOOST_CHECK(1 == o->which_ctor);
|
||||
|
||||
o.emplace(1, d);
|
||||
BOOST_CHECK(o);
|
||||
BOOST_CHECK(2 == o->which_ctor);
|
||||
|
||||
o.emplace(1, 2.0);
|
||||
BOOST_CHECK(o);
|
||||
BOOST_CHECK(3 == o->which_ctor);
|
||||
|
||||
o.emplace(i, d);
|
||||
BOOST_CHECK(o);
|
||||
BOOST_CHECK(4 == o->which_ctor);
|
||||
|
||||
o.emplace(cs);
|
||||
BOOST_CHECK(o);
|
||||
BOOST_CHECK(5 == o->which_ctor);
|
||||
|
||||
o.emplace(ms);
|
||||
BOOST_CHECK(o);
|
||||
BOOST_CHECK(6 == o->which_ctor);
|
||||
|
||||
o.emplace(std::string());
|
||||
BOOST_CHECK(o);
|
||||
BOOST_CHECK(7 == o->which_ctor);
|
||||
}
|
||||
|
||||
void test_clear_on_throw()
|
||||
{
|
||||
optional<Thrower> ot;
|
||||
try {
|
||||
ot.emplace(false);
|
||||
BOOST_CHECK(ot);
|
||||
} catch(...) {
|
||||
BOOST_CHECK(false);
|
||||
}
|
||||
|
||||
try {
|
||||
ot.emplace(true);
|
||||
BOOST_CHECK(false);
|
||||
} catch(...) {
|
||||
BOOST_CHECK(!ot);
|
||||
}
|
||||
}
|
||||
|
||||
void test_no_moves_on_emplacement()
|
||||
{
|
||||
try {
|
||||
optional<ThrowOnMove> o;
|
||||
o.emplace(1);
|
||||
BOOST_CHECK(o);
|
||||
}
|
||||
catch (...) {
|
||||
BOOST_CHECK(false);
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
int test_main( int, char* [] )
|
||||
{
|
||||
try
|
||||
{
|
||||
#if (!defined BOOST_NO_CXX11_RVALUE_REFERENCES) && (!defined BOOST_NO_CXX11_VARIADIC_TEMPLATES)
|
||||
test_emplace();
|
||||
test_clear_on_throw();
|
||||
test_no_moves_on_emplacement();
|
||||
#endif
|
||||
}
|
||||
catch ( ... )
|
||||
{
|
||||
BOOST_ERROR("Unexpected Exception caught!");
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user