Desqeh
Developer
The literal 0 has a unique position in C++ programming -- it automatically converts to almost every fundamental type, depending on the context:
In contemporary C++ programming, the only workaround is an explicit typecast expression that forces the compiler to select the desired function:
Using nullptr
The C++ standards committee has been aware of this problem for many years. However, a consensus about the right solution was reached only recently in the form of a new keyword that designated a null pointer value. nullptr is a C++0x reserved keyword designating an rvalue constant of type
std::nullptr_t.
nullptr is implicitly converted to pointers and pointers to members. However, it's not convertible to bool or any of the numeric types of C++.
You can use nullptr as an initializer for all pointer types and in comparison expressions:
A Solution to a Thorny Problem
The use of nullptr eliminates the overload resolution problem:
- Code:
int x=0;
double d=0;
char * pstr=0; //null pointer
int (A::*pmf)(int) =0; //null pointer to member
bool flag=0; //Boolean false
- Code:
void f(int); //#1
void f(char *);//#2
f(0); //which f is called?
- Code:
f(NULL); //calls f(int)!
In contemporary C++ programming, the only workaround is an explicit typecast expression that forces the compiler to select the desired function:
- Code:
f((char *)0); //unambiguous but still a kludge
Using nullptr
The C++ standards committee has been aware of this problem for many years. However, a consensus about the right solution was reached only recently in the form of a new keyword that designated a null pointer value. nullptr is a C++0x reserved keyword designating an rvalue constant of type
std::nullptr_t.
nullptr is implicitly converted to pointers and pointers to members. However, it's not convertible to bool or any of the numeric types of C++.
You can use nullptr as an initializer for all pointer types and in comparison expressions:
- Code:
const char *pc=str.c_str();
if (pc!=nullptr)
cout<<pc<<endl;
int (A::*pmf)()=nullptr; //pointer to member function
int A::*pmi=nullptr; //pointer to data member
- Code:
char* ps=nullptr; //OK
char c=nullptr; //error, type mismatch
int n=nullptr; //error, type mismatch
A Solution to a Thorny Problem
The use of nullptr eliminates the overload resolution problem:
- Code:
func(nullptr); //calls func (char*)
func(0); //calls func(int)
- Code:
cout<< typeid(nullptr).name();
size_t sz= sizeof(nullptr);
- Code:
try
{
if(failure)
throw nullptr; //OK
}
catch(std::nullptr_t)
{
cerr<<"terminating!";
}