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?
Solution:
How is it a keyword and an instance of a type?
This isn’t surprising. Both true and false are keywords and as literals they have a type ( bool ). nullptr is a pointer literal of type std::nullptr_t, and it’s a prvalue (you cannot take the address of it using &).
-
4.10about pointer conversion says that a prvalue of typestd::nullptr_tis 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 passingnullptrto select the pointer version. PassingNULLor0would confusingly select theintversion. -
A cast of
nullptr_tto an integral type needs areinterpret_cast, and has the same semantics as a cast of(void*)0to an integral type (mapping implementation defined). Areinterpret_castcannot convertnullptr_tto any pointer type. Rely on the implicit conversion if possible or usestatic_cast. -
The Standard requires that
sizeof(nullptr_t)besizeof(void*).