Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for a snapshot of the develop branch, built from commit 26d7d9b59f.
PrevUpHomeNext

Optional automatic variables

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 unitialized optional object. Unlike with ints 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.


PrevUpHomeNext