I have a few questions about how boost::optional
works. Let's first do this:
boost::optional<int> i;
i < 3
always equivalent to *i < 3
(and similar for other relational operators)?i < 3
and *i < 3
are undefined? (i
has still not been set to anything)std::cout << i
supposed to print?i = 3
is always the same as *i = 3
. If so, which should I prefer?i
is uninitialized, the first will return true while the second will assert.operator<
clearly indicates that if the lefthand argument is uninitialized it will return true
when the righthand operand is set.operator<<
for optional
so I assume it will return the unspecified-bool-type
conversion and print 1 or 0 (true/false).i
isn't initialized the latter will assert while the former will initialize-and-assign. You should use the one that indicates the semantics you desire.Regarding point 3, there is an operator<< for boost::optional declared in boost/optional/optional_io.hpp, but you probably aren't including that. (If you happen to use boost property_tree it gets included for you, though.) If it is included, an empty optional will stream as "--" and a populated optional will stream out an extra space character and then stream the value.
So this code:
#include <boost/optional/optional_io.hpp>
boost::optional<string> var1 = "value";
boost::optional<string> var2;
cout << " var1 = '" << var1 << "'\n";
cout << "*var1 = '" << *var1 << "'\n";
cout << " var2 = '" << var2 << "'\n";
yields this:
var1 = ' value'
*var1 = 'value'
var2 = '--'
but the same code without the include yields this, as suggested by Mark B's answer:
var1 = '1'
*var1 = 'value'
var2 = '0'
That extra space in the first case has caused me some confusion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With