Search code examples
c++boostboost-optional

Comparison (<), output (<<) and assignment (=) for boost::optional


I have a few questions about how boost::optional works. Let's first do this:

boost::optional<int> i;
  1. Is i < 3 always equivalent to *i < 3 (and similar for other relational operators)?
  2. Is it correct that the conditions i < 3 and *i < 3 are undefined? (i has still not been set to anything)
  3. What is std::cout << i supposed to print?
  4. I'm pretty sure that i = 3 is always the same as *i = 3. If so, which should I prefer?

Solution

    1. No. If i is uninitialized, the first will return true while the second will assert.
    2. No. The documentation for operator< clearly indicates that if the lefthand argument is uninitialized it will return true when the righthand operand is set.
    3. There is no operator<< for optional so I assume it will return the unspecified-bool-type conversion and print 1 or 0 (true/false).
    4. They aren't the same. If 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.