3

I am reviewing some code and have something like this:

boost::optional<bool> isSet = ...;
... some code goes here...
bool smthelse = isSet ? *isSet : false;

So my question is, is the last line equivalent to this:

bool smthelse = isSet; 
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76

2 Answers2

4

No they're not equivalent.

isSet ? *isSet : false; means if isSet contains a value then get the value, otherwise returns false.


BTW: bool smthelse = isSet; won't work because operator bool is declared as explicit.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
4

Here's the table:

boost::optional<bool> isSet | none | true | false |
----------------------------|------|------|-------|
isSet ? *isSet : false;     | false| true | false |
isSet                       | false| true | true  |

As you can see difference in the last column, where isSet has been assigned the boolean value false.

Alternatively, you can use isSet.get_value_or(false);.

Jarod42
  • 203,559
  • 14
  • 181
  • 302