We now have C++11 with many new features. An interesting and confusing one (at least for me) is the new nullptr
.
Well, no need anymore for the nasty macro NULL
.
int* x = nullptr;
myclass* obj = nullptr;
Still, I am not getting how nullptr
works. For example, Wikipedia article says:
C++11 corrects this by introducing a new keyword to serve as a distinguished null pointer constant: nullptr. It is of type nullptr_t, which is implicitly convertible and comparable to any pointer type or pointer-to-member type. It is not implicitly convertible or comparable to integral types, except for bool.
How is it a keyword and an instance of a type?
Also, do you have another example (beside the Wikipedia one) where nullptr
is superior to good old 0
?
Best Solution
This isn't surprising. Both
true
andfalse
are keywords and as literals they have a type (bool
).nullptr
is a pointer literal of typestd::nullptr_t
, and it's a prvalue (you cannot take the address of it using&
).4.10
about pointer conversion says that a prvalue of typestd::nullptr_t
is a null pointer constant, and that an integral null pointer constant can be converted tostd::nullptr_t
. The opposite direction is not allowed. This allows overloading a function for both pointers and integers, and passingnullptr
to select the pointer version. PassingNULL
or0
would confusingly select theint
version.A cast of
nullptr_t
to an integral type needs areinterpret_cast
, and has the same semantics as a cast of(void*)0
to an integral type (mapping implementation defined). Areinterpret_cast
cannot convertnullptr_t
to any pointer type. Rely on the implicit conversion if possible or usestatic_cast
.The Standard requires that
sizeof(nullptr_t)
besizeof(void*)
.