加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 将`nullptr`分配给`bool`类型.哪个编译器正确?

发布时间:2020-12-16 03:34:13 所属栏目:百科 来源:网络整理
导读:我有一小段代码将nullptr分配给bool类型. #include iostreamint main(){ bool b = nullptr; std::cout b;} 在clang 3.8.0工作正常.它给出了输出0. Clang Demo 但是g 5.4.0给出了一个错误: source_file.cpp: In function ‘int main()’:source_file.cpp:5:1
我有一小段代码将nullptr分配给bool类型.
#include <iostream>

int main()
{
    bool b = nullptr;
    std::cout << b;
}

在clang 3.8.0工作正常.它给出了输出0. Clang Demo

但是g 5.4.0给出了一个错误:

source_file.cpp: In function ‘int main()’:
source_file.cpp:5:18: error: converting to ‘bool’ from ‘std::nullptr_t’ requires direct-initialization [-fpermissive]
         bool b = nullptr;

哪个编译器正确?

解决方法

来自C标准(4.12布尔转换)

1 A prvalue of arithmetic,unscoped enumeration,pointer,or pointer
to member type can be converted to a prvalue of type bool. A zero
value,null pointer value,or null member pointer value is converted
to false; any other value is converted to true. For
direct-initialization (8.5),a prvalue of type std::nullptr_t can be
converted to a prvalue of type bool; the resulting value is false.

所以这个宣言

bool b( nullptr );

这是有效的

bool b = nullptr;

是错的.

我自己在isocpp已经指出了这个问题

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读