问题
I have a following snippet of code that assigned nullptr
to bool
type.
#include <iostream>
int main()
{
bool b = nullptr;
std::cout << b;
}
In clang 3.8.0 working fine. it's give an output 0
. Clang Demo
But g++ 5.4.0 give an error:
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;
Which compiler is correct?
回答1:
From the C++ Standard (4.12 Boolean conversions)
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.
So this declaration
bool b( nullptr );
is valid and this
bool b = nullptr;
is wrong.
I myself pointed out already this problem at isocpp
回答2:
This was changed by DR 1423 so that there is no implicit conversion from nullptr
to bool
.
(The relevant wording changed again very recently by 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.)
So it looks to me like Clang 3.8 implements the pre-1423 rule, and GCC 5.4 implements the post-1423 rule which doesn't allow implicit conversions from nullptr
to bool
.
Current versions of Clang still allow the conversion, but give a -Wnull-conversion
warning.
来源:https://stackoverflow.com/questions/46815821/assigned-nullptr-to-bool-type-which-compiler-is-correct