...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
We could write function convert
in a slightly different manner, so that it has a single return
-statement:
boost::optional<int> convert(const std::string& text) { boost::optional<int> ans; std::stringstream s(text); int i; if ((s >> i) && s.get() == std::char_traits<char>::eof()) ans = i; return ans; }
The default constructor of optional
creates an uninitialized optional object. Unlike with int
s
you cannot have an optional<int>
in an indeterminate state. Its state is always well defined. Instruction
ans =
i
initializes the optional object.
It uses the 'mixed' assignment from int
.
In general, for optional<T>
,
when an assignment from T
is invoked, it can do two things. If the optional object is not initialized
(our case here), it initializes the contained value using T
's
copy constructor. If the optional object is already initialized, it assigns
the new value to it using T
's
copy assignment.