1. nullptr necessity of introducing:
Typical pointer is initialized to point to a null position. such as:
int* my_ptr = 0;
int* my_ptr = NULL;
In general, NULL is a macro definition.
#undef NULL #if defined(__cplusplus) #define NULL 0 #else #define NULL ((void*)0) #endif
NULL literal may be defined as 0, or as defined untyped pointer (void *) constant.
The code shows the unexpected behavior caused by the use of NULL:
#include <stdio.h> void f(char* c) { printf("invoke f(char*)\n"); } void f(int i) { printf("invoke f(int)\n"); } int main() { f(0); f(NULL); f((char*)0); return 0; }
The output is:
invoke f(int)
invoke f (int) // NULL defined caused 0, 0 literal type may be either a plastic, or may be a non-pointer type (void *)
invoke f(char*)
2.nullptr definition:
typedef decltype(nullptr) nullptr_t;
Common rules on nullptr of:
(1) the definition of nullptr_t all types of data are equivalent, the behavior is exactly the same.
(2) nullptr_t types of data may be implicitly converted to a pointer of any type.
(3) nullptr_t type of data can not convert non-pointer type, even if reinterpret_cast <nullptr_t> () on the way can not.
(4) nullptr_t type data is not available for arithmetic expressions
(5) nullptr_t types of data may be used for relational operation expression, but only compared with nullptr_t type data or a pointer data type.
#include <the iostream> #include <the typeinfo> the using namespace STD; int main () { char * CP = nullptr a; // can not be converted to an integer // int N1 = nullptr a; // int reinterpret_cast N2 = <int> ( nullptr a); // nullptr a comparison can be made with the type nullptr_t nullptr_t nptr to; IF (== nptr to nullptr a) { COUT << " nullptr_t nptr to nullptr a == " << endl; } the else { COUT << " ! = nullptr a nptr to nullptr_t " <<endl; } IF (nptr to < nullptr a) { COUT << " nullptr_t nptr to <nullptr a " << endl; } the else { COUT << " ! nullptr_t nptr to <nullptr a " << endl; } // can not be converted to type bool // IF (nullptr a == 0) // IF (nullptr a) // not carried out arithmetic // nullptr a + =. 1; // nullptr a *. 5 // the following operating properly the sizeof (nullptr a); the typeid (nullptr a); the throw ( nullptr); return 0; }
3. The rules discussed
c ++ 11 standard, nullptr type data memory space occupied with the same void *.
sizeof(nullptr_t) == sizeof(void*)
nullptr is a compile-time constants, whose name is a keyword compile time, and can be recognized by the compiler.