C++11—引入nullprt

1. 引入nullptr的原因

引入nullptr的原因,這個要從NULL說起。對於C和C++程序員來說,一定不會對NULL感到陌生。但是C和C++中的NULL卻不等價。NULL表示指針不指向任何對象,但是問題在於,NULL不是關鍵字,而只是一個宏定義(macro)。

1.1 NULL在C中的定義

在C中,習慣將NULL定義爲void*指針值0:
  1. #define NULL (void*)0  
但同時,也允許將NULL定義爲整常數0

1.2 NULL在C++中的定義

在C++中,NULL卻被明確定義爲整常數0:
  1. // lmcons.h中定義NULL的源碼  
  2. #ifndef NULL  
  3. #ifdef __cplusplus  
  4. #define NULL    0  
  5. #else  
  6. #define NULL    ((void *)0)  
  7. #endif  
  8. #endif  

1.3爲什麼C++在NULL上選擇不完全兼容C?

根本原因和C++的重載函數有關。C++通過搜索匹配參數的機制,試圖找到最佳匹配(best-match)的函數,而如果繼續支持void*的隱式類型轉換,則會帶來語義二義性(syntax ambiguous)的問題。
  1. // 考慮下面兩個重載函數  
  2. void foo(int i);  
  3. void foo(char* p)  
  4.   
  5. foo(NULL); // which is called?  

2. nullptr的應用場景

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編譯選項)

2.2 使用方法

0(NULL)和nullptr可以交換使用,如下示例:
  1. int* p1 = 0;  
  2. int* p2 = nullptr;  
  3.   
  4. if(p1 == 0) {}  
  5. if(p2 == 0) {}  
  6. if(p1 == nullptr) {}  
  7. if(p2 == nullptr) {}  
  8. if(p1 == p2) {}  
  9. if(p2) {}  
不能將nullptr賦值給整形,如下示例:
  1. int n1 = 0;             // ok  
  2. int n2 = nullptr;       // error  
  3.   
  4. if(n1 == nullptr) {}    // error  
  5. if(n2 == nullptr) {}    // error  
  6. if(nullprt) {}          // error  
  7. nullptr = 0             // error  
上面提到的重載問題,使用nullptr時,將調用char*。
  1. void foo(int)   {cout << "int" << endl;}  
  2. void foo(char*) {cout << "pointer" << endl;}  
  3.   
  4. foo(0);       // calls foo(int)  
  5. foo(nullptr); // calls foo(char*)  

3. 模擬nullptr的實現

某些編譯器不支持c++11的新關鍵字nullptr,我們也可以模擬實現一個nullptr。
  1. const  
  2. class nullptr_t_t  
  3. {  
  4. public:  
  5.     template<class T>           operator T*() const {return 0;}  
  6.     template<class C, class T>  operator T C::*() const { return 0; }  
  7. private:  
  8.     void operator& () const;  
  9. } nullptr_t = {};  
  10. #undef NULL  
  11. #define NULL nullptr_t  
發佈了54 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章