2017-10-18 131 views
6

我有以下代码段,它分配了nullptrbool类型。将`nullptr`分配给`bool`类型。哪个编译器是正确的?

#include <iostream> 

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

铛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; 

哪个编译器是正确的?

+0

你链接的实时编译器在运行它时我得到一个编译器警告。 “警告:将nullptr常量隐式转换为'bool'[-Wullull-conversion]” – UnholySheep

+0

根据GCC(和MSVC)给出的错误和[reference]部分(http://en.cppreference.com/ w/cpp/language/implicit_conversion)我会说这是标准所不允许的(并且Clang允许它作为扩展名) – UnholySheep

+0

它应该不错。 'nullptr'的一个要点是使用布尔上下文中的指针来定义一个明确的事情。 : - /但是,我可以看到如何以这种转让的形式警告直接转化可能是正确的。当你有'nullptr && true'而不是'nullptr'时,编译器是否仍然出错? – Omnifarious

回答

8

从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

+1

C++ 11标准有不同的措词。请参阅https://timsong-cpp.github.io/cppwp/n3337/conv.bool。您的文章是否来自标准的更高版本? –

+1

虽然,为什么它按照OP所述在3.8.0版上正常工作?它有没有把'nullptr'解释为clang中的0? (虽然不太可能) –

+1

有没有失踪?我认为它应该是“所以这个声明是正确的”(对于第一个片段) – UnholySheep

相关问题