升压::可选<bool>取消引用

Boost::optional<bool> dereference

本文关键字:取消 引用 gt lt 可选 升压 bool      更新时间:2023-10-16

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

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

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

bool smthelse = isSet; 

下表如下:

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

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

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

不,

它们不等同。

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


顺便说一句:bool smthelse = isSet;不起作用,因为operator bool被声明为 explicit .