Reputation: 107
Why we can't directly assign nullptr to a bool object? For example, the flag object's assignment causes an error. Visual Studio compiler gives that: "C++ a value of type cannot be assigned to an entity of type".
int main(){
int x = 10;
int *ptr = &x;
bool flag = ptr;
flag = nullptr;
}
but below version works fine.
int main(){
int x = 10;
int *ptr = &x;
bool flag = ptr;
ptr = nullptr;
flag = ptr;
}
Upvotes: 2
Views: 271
Reputation: 41110
It's kind of tricky. We have to carefully examine the C++ standard. First, "Standard Conversions" states:
And this conversion simply just converts null pointers to false. So it seems like we should be able to directly assign a null pointer constant to a boolean, right?
Well, kind of.
See, the actual definition for nullptr
states that it is an instance of std::nullptr_t
, which is a distinct type that is NOT actually a pointer type. However, it can be converted to a pointer type! (Per [lex.nullptr]).
Still seems like it should be possible, right? nullptr
is convertible to a pointer type, which is convertible to a boolean.
However, a standard conversion (back to [conv]) sequence can only apply conversions in a specific order. This order allows only ONE of boolean OR pointer conversion.
So, the two conversions that we need will not happen implicitly. We would have to explicitly do one of them for the compiler. For example:
flag = static_cast<int*>(nullptr);
Or, possibly simpler
flag = bool{nullptr}
Or even simpler:
flag = {nullptr}
But at that point, you might as well just use false
:-)
Upvotes: 8