问题
Summary: nullptr
converts to bool
, and bool
converts to int
, so why doesn't nullptr
convert to int
?
This code is okay:
void f(bool);
f(nullptr); // fine, nullptr converts to bool
And this is okay:
bool b;
int i(b); // fine, bool converts to int
So why isn't this okay?
void f(int);
f(nullptr); // why not convert nullptr to bool, then bool to int?
回答1:
Because it is exactly the main idea of nullptr
.
nullptr
was meant to avoid this behavior:
struct myclass {};
void f(myclass* a) { std::cout << "myclass\n"; }
void f(int a) { std::cout << "int\n"; }
// ...
f(NULL); // calls void f(int)
If nullptr
were convertible to int
this behavior would occur.
So the question is "why is it convertible to bool
?".
Syntax-"suggarness":
int* a = nullptr;
if (a) {
}
Which looks way better than:
if (a == nullptr) {
}
回答2:
In §4.1 of the Standard, it says how conversions are performed:
Standard conversions are implicit conversions with built-in meaning. Clause 4 enumerates the full set of such conversions. A standard conversion sequence is a sequence of standard conversions in the following order:
— Zero or one conversion from the following set: lvalue-to-rvalue conversion, array-to-pointer conversion, and function-to-pointer conversion.
— Zero or one conversion from the following set: integral promotions, floating point promotion, integral conversions, floating point conversions, floating-integral conversions, pointer conversions, pointer to member conversions, and boolean conversions.
— Zero or one qualification conversion.
So the compiler only does "zero or one conversion" of some, none, or all of each of the above types of conversions, not arbitrarily many. And that's a really good thing.
回答3:
To understand why is this happening, you should understand how to use nullptr
. Check these links bellow:
- http://en.wikipedia.org/wiki/C%2B%2B11
- What exactly is nullptr?
I hope it helps.
回答4:
The keyworkd nullptr is introduced in c++11 because multiple definition of the C NULL, and it confuses when overloading a function with int arguments and NULL.
#define NULL 0
#define NULL (void*)0
In the bible The C++ Programming Language (4th), page 270
The pointer-to-bool conversion is useful in conditions, but confusing elsewhere.
So I think nullptr_t varible convert to int is not allowed because that's the reason why it exists, but it can be used as a test condition like bool variables.
来源:https://stackoverflow.com/questions/13092266/why-cant-nullptr-convert-to-int