3

我正在审查一些代码,并有这样的事情:

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

所以我的问题是,最后一行是否等同于:

bool smthelse = isSet; 
4

2 回答 2

4

不,它们不相等。

isSet ? *isSet : false;表示如果isSet包含一个值则获取该值,否则返回false


顺便说一句:bool smthelse = isSet;因为operator bool被声明为explicit.

于 2018-01-30T13:36:02.357 回答
4

这是表格:

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

正如您在最后一列中看到的差异,其中isSet已分配了布尔值false

或者,您可以使用isSet.get_value_or(false);.

于 2018-01-30T13:53:02.663 回答