Search code examples
c++boostbooleanoption-typeboost-optional

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; 

Solution

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