在我們C++的代碼的使用時(shí)我常用NULL作為空指針的判斷,或者指針的賦空,如下代碼:
#include "pch.h"
#include <iostream>
void test(char *p)
{
printf("this is p");
}
int main()
{
test(NULL);
}
代碼輸出:
this is p
但是,在C++中,NULL的定義是 0
- ps:在C語(yǔ)言中,NULL 的定義是 (void*)空指針
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
因?yàn)樵贑++中,(void*)不能隱式的轉(zhuǎn)換為其他指針類型。所以使用int類型的0轉(zhuǎn)換為各種類型的空指針。
在這種情況下我們會(huì)出現(xiàn)一些二義性:
#include "pch.h"
#include <iostream>
void test(int n)
{
printf("this is int");
}
void test(char *p)
{
printf("this is p");
}
int main()
{
test(NULL);
}
運(yùn)行結(jié)果:
this is int
我認(rèn)為NULL是空指針的意思,但是調(diào)用卻不是。
nullptr是C++11用來(lái)解決這個(gè)問(wèn)題引入的,專門用于處理空指針的情況。
如下:
#include "pch.h"
#include <iostream>
void test(int n)
{
printf("this is int");
}
void test(char *p)
{
printf("this is p");
}
int main()
{
test(NULL);
printf("\n");
test(nullptr);
}
運(yùn)行輸出:
this is int
this is p