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:
[CPP]View Plaincopyprint?
- #define NULL (void*) 0
However, it is also possible to define null 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:
[CPP]View Plaincopyprint?
- 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).
[CPP]View Plaincopyprint?
- Consider the following two overloaded functions
- void foo (int i);
- void foo (char* p)
- Foo (NULL); //which is called?
2. Application scenario for nullptr 2.1 compiler
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:
[CPP]View Plaincopyprint?
- int n1 = 0; //OK
- int n2 = nullptr; //Error
- if (n1 = = nullptr) {} //Error
- if (N2 = = nullptr) {} //Error
- if (nullprt) {} //Error
- nullptr = 0 //Error
The above mentioned overload problem, when using nullptr, will call char*.
[CPP]View Plaincopyprint?
- void foo (int) {cout << "int" << Endl;}
- void foo (char*) {cout << "pointer" << Endl;}
- Foo (0); //calls foo (int)
- Foo (nullptr); //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.
Constclassnullptr_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
C + + 11nullptr