1. Reasons for introducing nullptr
The reason for introducing nullptr, this is to start from null. For C and C + + programmers, you must not be unfamiliar with null. However, NULL in C and C + + is not equivalent. Null indicates that the pointer does not point to any object, but the problem is that NULL is not a keyword, but just a macro definition.
1.1 The definition of NULL in C
In C, it is customary to define null as the void* pointer value 0:
#define NULL (void*) 0
However, NULL is also allowed to be defined as an integer constant of 0.
1.2 The definition of NULL in C + +
In C + +, NULL is explicitly defined as an integer constant of 0:
// source of NULL in Lmcons.h #ifndef null #ifdef __cplusplus #define null 0 #else #define NULL ((void *) 0) #endif #endif
1.3 Why is C + + not fully compatible with C on null?
The root cause is related to the overloaded functions of C + +. C + + attempts to find the best match (best-match) function by searching for a mechanism for matching parameters, and if continuing to support implicit type conversion of void*, it brings up the problem of semantic ambiguity (syntax ambiguous).
// consider the following two overloaded functions void foo (int i); void foo (char* p) // which is called?
2. NULLPTR's application Scenario
2.1 Compilers
If our compiler supports NULLPTR, then we should use nullptr directly instead of the null macro definition. They are completely equivalent during normal use. For compilers, Visual Studio 2010 has started to support most of the features in c++0x, naturally including nullptr. This keyword is not supported in previous versions of VS2010. g++ 4.4.1 included with Codeblocks10.5 does not support nullptr, 4.6.1 can be supported after upgrade to NULLPTR (requires-std=c++0x compile option)
2.2 How to use
0 (NULL) and nullptr can be used interchangeably, as in the following example:
int 0 ; int* P2 = nullptr; if 0 {}if0) { }if(p1 = = nullptr) {} if (P2 = = nullptr) { } if (P1 = = p2) { } if (p2) {}
NULLPTR cannot be assigned to reshape, as in the following example:
int n1 = 0 ; // OK int n2 = nullptr; // error if (N1 = = nullptr) {} // error (n2 = = nullptr) {} // error if (nullprt) {} // error Nullpt r = 0 error
The above mentioned overload problem, when using nullptr, will call char*.
void foo (int) "int" << Endl;} void foo (char"pointer" << Endl;} Foo (0); // calls foo (int) // calls Foo (char*)
3. Implementation of the analog nullptr
Some compilers do not support c++11 's new keyword nullptr, and we can also simulate implementing a nullptr.
Const classnullptr_t_t { Public: Template<classT>operatorT* ()Const{return 0;} Template<classCclassT>operatorT C::* ()Const{return 0; } Private: void operator& ()Const; } nullptr_t= {}; #undefNull#defineNULL nullptr_t
"Turn from" http://blog.csdn.net/huang_xw/article/details/8764346
Three--nullptr of new characteristics of c++11