Usage
nullptr is a reserved keyword designating an
rvalue constant of type
std::nullptr_t. The underlying type of
std::nullptr_t is implementation-defined. However, it must be a
POD type, whose size is the same as
sizeof(void*).
nullptr is implicitly converted to pointers and pointers to members. However,
nullptr is not convertible to
bool or any of the numeric types of C++:
//pointers and numeric types
char *pc=nullptr; //OK
char c=nullptr; //error, type mismatch
int num=nullptr; //error, type mismatch
//pointers to members
int (A::*pmf)(char *)=nullptr; //OK
int A::*pmi=nullptr; //OK, pointer to data member
//comparisons
if (nullptr==0) //error, type mismatch
if (nullptr)//error, conversion to bool not allowed
if (pc==nullptr) //OK
See how
nullptr elegantly solves the overload resolution problem shown earlier:
void func(int);
void func(char *);
int main()
{
func(nullptr); //calls func (char*)
func(0); //calls func(int)
}
nullptr can be used in a
sizeof expression. Additionally, you can use
nullptr as the argument of a
typeid expression:
cout<< typeid(nullptr).name(); //OK
size_t n= sizeof(nullptr); //n=sizeof(void *).
Throwing and copying
nullptr_t objects is also allowed. In the following code listing, the
throw statement inside the
try block throws
nullptr. The matching
catch block catches this object by value:
try
{
throw nullptr; //OK
}
catch(std::nullptr_t np)
{}
Notice that you cannot take the address of
nullptr, though it is possible to take the address of another object of type
std::nullptr_t:
template <typename T> void func(T) {/**/}
func (&nullptr); //error, can't take nullptr's address
std::nullptr_t nullp;
func(&nullp);//OK
Future Directions
The latest draft of the nullptr proposal is available
here. Although C++ compilers don't support this feature yet, you can use macros to ensure smooth migration to
nulltpr in the near future:
#ifndef __CPP09NULLPTRSUPPORTED
#define NULLPTR (0)
#else
#define NULLPTR (nullptr)
#endif
C++09 will retain compatibility with older versions of C++. Therefore, 0 will remain in use as a null pointer constant in C++09, in addition to the normative
nullptr:
char *pc=0; //OK, pc is a null pointer even in C++09
if(ch1==nullptr) //OK
Similarly, the current definition of the macro
NULL will not change in C++09.