Eduard Rostomyan
Eduard Rostomyan

Reputation: 6546

Boost::optional<bool> dereference

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; 

Upvotes: 3

Views: 1069

Answers (2)

Jarod42
Jarod42

Reputation: 217165

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);.

Upvotes: 4

songyuanyao
songyuanyao

Reputation: 172894

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.

Upvotes: 4

Related Questions