2017-10-18 133 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

相關問題