c++ - 将 `nullptr` 分配给 `bool` 类型。哪个编译器是正确的?

标签 c++ gcc boolean clang nullptr

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

#include <iostream>

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

clang 3.8.0 中工作正常。它给出了输出 0Clang 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 boolean 转换)

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 指出了这个问题

关于c++ - 将 `nullptr` 分配给 `bool` 类型。哪个编译器是正确的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46815821/

相关文章:

c++ - 使用 C++ lambda Unresolved external 问题

c++ - 预编译器会评估位移位和算术运算吗?

Java 循环输入流直到 boolean = false

c - 当我在 c 中使用 strlcpy 函数时,编译器给我一个错误

C# boolean 操作来检测任何错误返回

c# - C# 中的 boolean 属性

c++ - 使用 QProcess 读取标准输出

c++ - Qt Creator - SFML 链接到控制台项目

python - 将两个使用 C++ 流的共享库导入 python 会导致输出损坏

c - 如何在 C 中将多个字符串值存储到一个字符串中?