Anirudh
Anirudh

Reputation: 349

Right way to use boost::optional

I see two ways of accessing a boost::optional variable:

  1. The dereference operator on the variable
  2. The variable itself

If I have this code snippet:

#include <boost/optional.hpp>
#include <iostream>

int main()
{
  boost::optional<int> oi;
  std::cout << oi << "\n";
}

(where oi is uninitialized) and compile it using "g++-4.9 /tmp/optional.cc" followed by ./a.out, I get 0,

but with this:

#include <boost/optional.hpp>
#include <iostream>

int main()
{
  boost::optional<int> oi;
  std::cout << *oi << "\n";
}

I get:

a.out: /usr/include/boost/optional/optional.hpp:631: boost::optional<T>::reference_type boost::optional<T>::get() [with T = int; boost::optional<T>::reference_type = int&]: Assertion `this->is_initialized()' failed.
Aborted (core dumped)

which is the expected behavior.

Upvotes: 0

Views: 3323

Answers (2)

andreycpp
andreycpp

Reputation: 1179

boost::optional<T> ostream helpers are actually available since boost 1.34. See http://www.boost.org/doc/libs/1_34_0/boost/optional/optional_io.hpp

Note that one needs to EXPLICITLY include <boost/optional/optional_io.hpp> to enable these helpers. It is NOT included by <boost/optional.hpp>.

Upvotes: 0

T.C.
T.C.

Reputation: 137310

You must have been using an older version of Boost. Your first case triggered a conversion to bool; since the optional does not contain a value, the result of the conversion is false, which is printed as 0.

Newer versions (1.56-1.57) added an operator<< function template declaration to <boost/optional.hpp>

template<class CharType, class CharTrait, class T>
std::basic_ostream<CharType, CharTrait>&
operator<<(std::basic_ostream<CharType, CharTrait>& out, optional<T> const& v);

to catch this kind of mistakes and cause a linker error instead.

Note that including <boost/optional/optional_io.hpp> allows you to actually use the stream operators with optional, in which case optionals that do not contain a value are printed as --.

Upvotes: 1

Related Questions