【问题标题】:Boost::optional<bool> dereferenceBoost::optional<bool> 取消引用
【发布时间】:2018-01-30 13:33:26
【问题描述】:

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

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

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

bool smthelse = isSet; 

【问题讨论】:

  • bool smthelse = isSet.get_value_or(false); 可能更容易阅读。

标签: c++ boost boolean optional boost-optional


【解决方案1】:

这是桌子:

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

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

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

【讨论】:

    【解决方案2】:

    不,它们不相等。

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


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

    【讨论】:

    • 我的意思是,这种情况下结果会不一样?
    • @EduardRostomyan 当isSet 包含一个布尔值,但该值为false。
    • 在这种情况下,smthelse 的值也会为 false,不是吗?
    • @EduardRostomyan 你是说isSet 还是*isSet?它们是不同的东西。
    猜你喜欢
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多