C++11新特性-引入关键字nullptr

1. 引入nullptr的缘由

引入nullptr的缘由,这个要从NULL提及。对于C和C++程序员来讲,必定不会对NULL感到陌生。可是C和C++中的NULL却不等价。NULL表示指针不指向任何对象,可是问题在于,NULL不是关键字,而只是一个宏定义(macro)。
c++

1.1 NULL在C中的定义

在C中,习惯将NULL定义为void*指针值0:程序员

#define NULL (void*)0

但同时,也容许将NULL定义为整常数0
函数

1.2 NULL在C++中的定义

在C++中,NULL却被明肯定义为整常数0:
spa

// lmcons.h中定义NULL的源码  
#ifndef NULL  
#ifdef __cplusplus  
#define NULL    0  
#else  
#define NULL    ((void *)0)  
#endif  
#endif

1.3为何C++在NULL上选择不彻底兼容C?

根本缘由和C++的重载函数有关。C++经过搜索匹配参数的机制,试图找到最佳匹配(best-match)的函数,而若是继续支持void*的隐式类型转换,则会带来语义二义性(syntax ambiguous)的问题。指针

// 考虑下面两个重载函数  
void foo(int i);  
void foo(char* p)  
  
foo(NULL); // which is called?

2. nullptr的应用场景
c++11

2.1 编译器

若是咱们的编译器是支持nullptr的话,那么咱们应该直接使用nullptr来替代NULL的宏定义。正常使用过程当中他们是彻底等价的。
对于编译器,Visual Studio 2010已经开始支持C++0x中的大部分特性,天然包括nullptr。而VS2010以前的版本,都不支持此关键字。
Codeblocks10.5附带的G++ 4.4.1不支持nullptr,升级为4.6.1后可支持nullptr(需开启-std=c++0x编译选项或者-std=c++11)
code

2.2 使用方法

0(NULL)和nullptr能够交换使用,以下示例:
对象

int* p1 = 0;  
int* p2 = NULL;
int* p3 = nullptr;  
  
if(p1 == 0) {}  
if(p2 == 0) {}  
if(p3 == 0) {}
if(p1 == nullptr) {}  
if(p2 == nullptr) {}  
if(p3 == nullptr) {}  
if(p1 == p2) {}  
if(p2 == p3) {} 
if(p1) {}
if(p2) {}
if(p3) {}

不能将nullptr赋值给整形,以下示例:
编译器

int n1 = 0;             // ok 
int n2 = NULL;          //warning 
int n3 = nullptr;       // error  
int n4 = (int)NULL;     //ok
int n5 = (int)nullptr;  //error
  
if(n1 == nullptr) {}    // error  
if(n2 == nullptr) {}    // error  
if(nullptr) {}          // error  
nullptr = 0             // error

可见,nullptr要比NULL要求更加严格。源码

上面提到的重载问题,使用nullptr时,将调用char*。

void foo(int)   {cout << "int" << endl;}  
void foo(char*) {cout << "pointer" << endl;}  
  
foo(0);       // calls foo(int)  
foo(nullptr); // calls foo(char*)

3. 模拟nullptr的实现

某些编译器不支持c++11的新关键字nullptr,咱们也能够模拟实现一个nullptr。

const  
class nullptr_t_t  
{  
public:  
    template<class T>           operator T*() const {return 0;}  
    template<class C, class T>  operator T C::*() const { return 0; }  
private:  
    void operator& () const;  
} nullptr_t = {};  
#undef NULL  
#define NULL nullptr_t
相关文章
相关标签/搜索