- 引入nullptr的原因
引入nullptr的原因,這個要從NULL說起。對于C和C++程序員來說,一定不會對NULL感到陌生。但是C和C++中的NULL卻不等價。NULL表示指針不指向任何對象,但是問題在于,NULL不是關(guān)鍵字,而只是一個宏定義(macro)。
1.1 NULL在C中的定義
在C中,習慣將NULL定義為void*指針值0:
#define NULL (void*)0
但同時,也允許將NULL定義為整常數(shù)0
1.2 NULL在C++中的定義
在C++中,NULL卻被明確定義為整常數(shù)0:
// lmcons.h中定義NULL的源碼
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
1.3為什么C++在NULL上選擇不完全兼容C?
根本原因和C++的重載函數(shù)有關(guān)。C++通過搜索匹配參數(shù)的機制,試圖找到最佳匹配(best-match)的函數(shù),而如果繼續(xù)支持void*的隱式類型轉(zhuǎn)換,則會帶來語義二義性(syntax ambiguous)的問題。
// 考慮下面兩個重載函數(shù)
void foo(int i);
void foo(char* p)
foo(NULL); // which is called?
- nullptr的應用場景
2.1 編譯器
如果我們的編譯器是支持nullptr的話,那么我們應該直接使用nullptr來替代NULL的宏定義。正常使用過程中他們是完全等價的。對于編譯器,Visual Studio 2010已經(jīng)開始支持C++0x中的大部分特性,自然包括nullptr。而VS2010之前的版本,都不支持此關(guān)鍵字。Codeblocks10.5附帶的G++ 4.4.1不支持nullptr,升級為4.6.1后可支持nullptr(需開啟-std=c++0x編譯選項)
2.2 使用方法
0(NULL)和nullptr可以交換使用,如下示例:
int* p1 = 0;
int* p2 = nullptr;
if(p1 == 0) {}
if(p2 == 0) {}
if(p1 == nullptr) {}
if(p2 == nullptr) {}
if(p1 == p2) {}
if(p2) {}
不能將nullptr賦值給整形,如下示例:
int n1 = 0; // ok
int n2 = nullptr; // error
if(n1 == nullptr) {} // error
if(n2 == nullptr) {} // error
if(nullprt) {} // error
nullptr = 0 // error
上面提到的重載問題,使用nullptr時,將調(diào)用char*。
void foo(int) {cout << "int" << endl;}
void foo(char*) {cout << "pointer" << endl;}
foo(0); // calls foo(int)
foo(nullptr); // calls foo(char*)
- 模擬nullptr的實現(xiàn)
某些編譯器不支持c++11的新關(guān)鍵字nullptr,我們也可以模擬實現(xiàn)一個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