對(duì)于有經(jīng)驗(yàn)的C ++和那些了解現(xiàn)代C ++編程語(yǔ)言的人來(lái)說(shuō),C ++中的nullptr到底是什么,這將是非常簡(jiǎn)單的問(wèn)題。但是nullptr不僅是C ++中的編程語(yǔ)言,而且為了解釋這一點(diǎn),我們先了解一下NULL的問(wèn)題,然后我們將深入研究nullptr的簡(jiǎn)單實(shí)現(xiàn)以及nullptr的一些用例。為什么我們需要nullptr?區(qū)分整數(shù)0(零)(即NULL)和類(lèi)型指針的實(shí)際null。
nullptr與NULL
NULL為0(零),即將C樣式類(lèi)型轉(zhuǎn)換為void *的整數(shù)常數(shù)為零,而nullptr是nullptr_t類(lèi)型的prvalue,該值是整數(shù)常量,其值為零。
對(duì)于那些相信NULL相同的人,即C和C ++中的(void *)0。想澄清的是,不是:
NULL-cppreference.com (C)
NULL-cppreference.com (C ++)
C ++要求將宏NULL定義為值為0的整數(shù)常量表達(dá)式。因此與C語(yǔ)言不同,在C ++標(biāo)準(zhǔn)庫(kù)中不能將NULL定義為(void *)0。
NULL問(wèn)題
1.隱式轉(zhuǎn)換
char *str = NULL; // Implicit conversion from void * to char *
int i = NULL; // OK, but `i` is not pointer type
2.函數(shù)調(diào)用歧義
void func(int) {}
void func(int*){}
void func(bool){}
func(NULL); // Which one to call?
編譯會(huì)產(chǎn)生以下錯(cuò)誤:
error: call to 'func' is ambiguous
func(NULL);
^~~~
note: candidate function void func(bool){}
^
note: candidate function void func(int*){}
^
note: candidate function void func(int){}
^
1error generated.
compiler exit status 1
3.構(gòu)造函數(shù)重載
struct String
{
String(uint32_t) { /* size of string */ }
String(const char*) { /* string */ }
};
String s1( NULL );
String s2( 5 );
在這種情況下,需要顯式轉(zhuǎn)換(即String s((char *)0))。
簡(jiǎn)單的nullptr的實(shí)現(xiàn)
nullptr是“ 返回類(lèi)型解析器” 慣用語(yǔ)的一個(gè)細(xì)微示例, 可以根據(jù)要為其分配實(shí)例的類(lèi)型自動(dòng)推斷出正確類(lèi)型的空指針。
考慮以下最簡(jiǎn)單且不復(fù)雜的nullptr實(shí)現(xiàn):
struct nullptr_t
{
void operator&() const = delete; // Can't take address of nullptr
template
inline operator T*() const { return 0; }
template
inline operator T C::*() const { return 0; }
};
nullptr_t nullptr;
如果上面的代碼對(duì)您來(lái)說(shuō)似乎很奇怪和怪異(盡管應(yīng)該不會(huì)),那么我建議您閱讀我之前有關(guān)高級(jí)C ++概念的文章。這里的魔術(shù)只是模板化轉(zhuǎn)換運(yùn)算符。
如果您有更權(quán)威的資料,那么這里是LLVM header中nullptr的具體實(shí)現(xiàn)。
nullptr的用例
struct C { void func(); };
int main(void)
{
int *ptr = nullptr; // OK
void (C::*method_ptr)() = nullptr; // OK
nullptr_t n1, n2;
n1 = n2;
//nullptr_t *null = &n1; // Address can't be taken.
}
如上例所示,當(dāng)將nullptr分配給整數(shù)指針時(shí),將創(chuàng)建模板化轉(zhuǎn)換函數(shù)的int類(lèi)型實(shí)例,方法也是如此。
這樣,通過(guò)利用模板功能,實(shí)際上每次創(chuàng)建新類(lèi)型分配時(shí),我們實(shí)際上都在創(chuàng)建適當(dāng)類(lèi)型的空指針。
由于nullptr是值為零的整數(shù)文字,因此您無(wú)法使用通過(guò)刪除運(yùn)算符完成的地址。
1.函數(shù)使用nullptr調(diào)用清晰度
void func(int) { /* ... */}
void func(int *) { /* ... */}
void func(bool) { /* ... */}
func(nullptr);
現(xiàn)在,func(int *)將被調(diào)用,因?yàn)閚ullptr將隱式推導(dǎo)為int *。
2.在nullptr_t上進(jìn)行類(lèi)型轉(zhuǎn)換
將nullptr_t強(qiáng)制轉(zhuǎn)換為整數(shù)類(lèi)型需要reinterpret_cast,并且具有與(void *)0強(qiáng)制轉(zhuǎn)換為整數(shù)類(lèi)型相同的語(yǔ)義。
只要目標(biāo)類(lèi)型足夠大,就將nullptr_t強(qiáng)制轉(zhuǎn)換為整數(shù)類(lèi)型。考慮一下:
// int ptr_not_ok = reinterpret_cast(nullptr); // Not OK
long ptr_ok = reinterpret_cast(nullptr); // OK
reinterpret_cast無(wú)法將nullptr_t轉(zhuǎn)換為任何指針類(lèi)型。請(qǐng)改用static_cast。
void func(int*) { /*...*/ }
void func(double*) { /*...*/ }
func(nullptr); // compilation error, ambiguous call!
// func(reinterpret_cast
func(static_cast
nullptr可以隱式轉(zhuǎn)換為任何指針類(lèi)型,因此使用static_cast進(jìn)行顯式轉(zhuǎn)換僅有效。
3.nullptr_t可比
int *ptr = nullptr;
if (ptr == 0); // OK
if (ptr <= nullptr); // OK
int a = 0;
if (a == nullptr); // error: invalid operands of types 'int' and 'std::nullptr_t' to binary 'operator=='
來(lái)自 Wikipedia:-…空指針常量:nullptr。它的類(lèi)型為nullptr_t,它可以隱式轉(zhuǎn)換,并且可以與任何指針類(lèi)型或指針到成員類(lèi)型進(jìn)行比較。
-除了布爾值,它不能隱式轉(zhuǎn)換或與整數(shù)類(lèi)型媲美。
const int a = 0;
if (a == nullptr); // OK
const int b = 5;
if (b == nullptr); // error: invalid operands of types 'const int' and 'std::nullptr_t' to binary 'operator=='
4.模板參數(shù)的類(lèi)型為std :: nullptr_t
template
void ptr_func(T *t) {}
ptr_func(nullptr); // Can not deduce T
如前所述,Return Type Resolver需要一個(gè)受讓人來(lái)推斷類(lèi)型。
template
void val_func(T t) {}
val_func(nullptr); // deduces T = nullptr_t
val_func((int*)nullptr); // deduces T = int*, prefer static_cast though
5.從nullptr_t轉(zhuǎn)換為bool
從cppreference中:
-在直接初始化的上下文中 ,可以從std :: nullptr_t類(lèi)型的prvalue初始化bool對(duì)象 ,包括nullptr。結(jié)果值為false。但是,這不被視為隱式轉(zhuǎn)換。
轉(zhuǎn)換僅允許直接初始化,而不允許復(fù)制初始化,其中包括按值將參數(shù)傳遞給函數(shù)的情況。例如:
bool b1 = nullptr; // Not OK
bool b2 {nullptr}; // OK
void func(bool){}
func(nullptr); // Not OK, need to do func(static_cast(nullptr));
6.雜項(xiàng)
typeid(nullptr); // OK
throw nullptr; // OK
char *ptr = expr ? nullptr : nullptr; // OK
// char *ptr1 = expr ? 0 : nullptr; // Not OK, types are not compatible
static_assert(sizeof(NULL) == sizeof(nullptr_t));
常見(jiàn)問(wèn)題匯總
何時(shí)引入nullptr?
C ++ 11
nullptr是關(guān)鍵字還是std :: nullptr_t類(lèi)型的實(shí)例?
true和false都是關(guān)鍵字和文字,因?yàn)樗鼈兌加幸粋€(gè)類(lèi)型(bool)。nullptr是類(lèi)型為std :: nullptr_t 的指針文字,它是一個(gè)prvalue,即純 rvalue,您不能使用&來(lái)獲取它的地址更多。
使用nullptr有什么優(yōu)勢(shì)?
重載集之間沒(méi)有函數(shù)調(diào)用歧義。
您可以使用nullptr_t進(jìn)行模板專(zhuān)業(yè)化。
代碼將變得更加安全,直觀和富有表現(xiàn)力。如果(ptr == nullptr); 而不是if(ptr == 0);。
C ++中的NULL是否等于C ++ 11中的nullpt?
一點(diǎn)也不。以下行甚至無(wú)法編譯:
cout<
可以將nullptr轉(zhuǎn)換為bool嗎?
是,但僅當(dāng)直接初始化時(shí)。即bool is_false {nullptr};。否則需要使用static_cast。
如何定義nullptr?
它只是被稱(chēng)為Return Type Resolver的模板化轉(zhuǎn)換運(yùn)算符。
通過(guò)上述介紹,C ++中的nullptr到底是什么相信大家已經(jīng)清楚了吧,如果想了解更多關(guān)于C ++的信息,請(qǐng)繼續(xù)關(guān)注中培偉業(yè)。