在我们C++的代码的使用时我常用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语言中,NULL 的定义是 (void*)空指针
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
因为在C++中,(void*)不能隐式的转换为其他指针类型。所以使用int类型的0转换为各种类型的空指针。
在这种情况下我们会出现一些二义性:
#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);
}
运行结果:
this is int
我认为NULL是空指针的意思,但是调用却不是。
nullptr是C++11用来解决这个问题引入的,专门用于处理空指针的情况。
如下:
#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);
}
运行输出:
this is int
this is p