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 mac
Let me first give you an implementation of unsophisticated nullptr_t
struct nullptr_t
{
void operator&() const = delete; // Can't take address of nullptr
template
inline operator T*() const { return 0; }
template
inline operator T C::*() const { return 0; }
};
nullptr_t nullptr;
nullptr is a subtle example of Return Type Resolver idiom to automatically deduce a null pointer of the correct type depending upon the type of the instance it is assigning to.
int *ptr = nullptr; // OK
void (C::*method_ptr)() = nullptr; // OK
nullptr
is being assigned to an integer pointer, a int
type instantiation of the templatized conversion function is created. And same goes for method pointers too.nullptr
is an integer literal with value zero, you can not able to use its address which we accomplished by deleting & operator.nullptr
in the first place?NULL
has some issue with it as below:char *str = NULL; // Implicit conversion from void * to char *
int i = NULL; // OK, but `i` is not pointer type
void func(int) {}
void func(int*){}
void func(bool){}
func(NULL); // Which one to call?
error: call to 'func' is ambiguous
func(NULL);
^~~~
note: candidate function void func(bool){}
^
note: candidate function void func(int*){}
^
note: candidate function void func(int){}
^
1 error generated.
compiler exit status 1
struct String
{
String(uint32_t) { /* size of string */ }
String(const char*) { /* string */ }
};
String s1( NULL );
String s2( 5 );
String s((char*)0))
.