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

Assigned `nullptr` to `bool` type. Which compiler is correct?

我有以下代码片段,将 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 布尔转换)

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

指出了这个问题

这已被 DR 1423 更改,因此没有从 nullptrbool 的隐式转换。

(最近 DR 1781 and DR 2133 but only to move the wording, not change what conversions are valid. At the time of writing, the CWG issues list doesn't show that 1781 has been resolved, but the change to the draft is at visible in git 再次更改了相关措辞。)

所以在我看来,Clang 3.8 实现了 pre-1423 规则,而 GCC 5.4 实现了 post-1423 规则,该规则不允许从 nullptr 到 [=11] 的隐式转换=].

当前版本的 Clang 仍然允许转换,但给出 -Wnull-conversion 警告。