将`nullptr`分配给`bool`类型.哪个编译器正确? [英] Assigned `nullptr` to `bool` type. Which compiler is correct?

查看:254
本文介绍了将`nullptr`分配给`bool`类型.哪个编译器正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码片段,将nullptr分配给bool类型.

I have a following snippet of code that assigned nullptr to bool type.

#include <iostream>

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

clang 3.8.0 中可以正常工作.它给出一个输出0. Clang演示

In clang 3.8.0 working fine. it's give an output 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布尔转换)

From the C++ Standard (4.12 Boolean conversions)

1算术,无作用域枚举,指针或指针的prvalue 成员类型可以转换为bool类型的prvalue.零 值,空指针值或空成员指针值被转换 虚假其他任何值都将转换为true. 对于 直接初始化(8.5),类型为std :: nullptr_t的prvalue可以是 转换为bool类型的prvalue;结果值为false.

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

这篇关于将`nullptr`分配给`bool`类型.哪个编译器正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆