3.C++中NULL和nullptr区别
3.C++中NULL和nullptr区别
1.NULL是什么
在《NULL,0,'\0',"0","\0"的区别》一文中,我们已经知道了在C中NULL是什么,在C的头文件中,通常定义如下:
#define NULL ((void*)0)
但是在C++中,它是这样定义的:
#define NULL 0
可以在stddef.h看到完整的这段:
#undef NULL
#if defined(__cplusplus)
#define NULL 0
#else
#define NULL ((void *)0)
#endif
也就是说,在C++中,NULL不过也是0罢了,把它当成空指针只是一个无可奈何的选择罢了。
那么为什么在C++和C中不一样呢?因为C++中不能将void *类型的指针隐式转换成其他指针类型,从下面的例子可以看出来:
//null.cpp
#include<iostream>
int main(void)
{
char p[] = "12345";
int *a = (void*)p;
return 0;
}
编译:
$ g+ -o null null.cpp
null.cpp: In function 'int main()':
null.cpp:5:17: error: invalid conversion from 'void*' to 'int*' [-fpermissive]
int *a =(void*)p;
所以不能将NULL定义为(void*)0。
2.nullptr
nullptr并非整型类别,甚至也不是指针类型,但是能转换成任意指针类型。nullptr的实际类型是std:nullptr_t。
2.1为什么该使用nullptr
回到最开始的问题,为什么作为指针的语义,我们应该使用nullptr,而不是NULL。 请看下面的代码:
#include<iostream>
using namespace std;
void test(void *p)
{
cout<<"p is pointer "<<p<<endl;
}
void test(int num)
{
cout<<"num is int "<<num<<endl;
}
int main(void)
{
test(NULL);
return 0;
}
编译:
$ g++ -o test test.cpp
main.cpp: In function ‘int main()’:
main.cpp:16:14: error: call of overloaded ‘test(NULL)’ is ambiguous
test(NULL);
很不幸,编译报错了,提示我们有二义性,两个都可以匹配,因此最终报错。
但是如果我们使用nullptr却不会:
test(nullptr);
除了这点之外,在C++模板中它还有更好的表现。 看下面的代码:
#include<iostream>
using namespace std;
template<typename Type1,typename ptrType>
void test(Type1 fun, ptrType ptr)
{
/*do something*/
fun(ptr);
return;
}
void fun(int *val)
{
cout<<"fun"<<endl;
}
int main(void)
{
test(fun, NULL);
return 0;
}
编译报错了:
main.cpp:8:8: error: invalid conversion from ‘long int’ to ‘int*’ [-fpermissive]
fun(ptr);
很显然NULL被推导为long int,而不是空指针,因而导致函数类型不匹配而报错。
但是如果我们用nullptr就不会有上面的问题。
注:nullptr在C++ 11中才出现。
参考:[(9条消息) nullptr与NULL的区别_nullptr和null区别_qq_37032670的博客-CSDN博客]
分类:
C++重点 / C++11新标准
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)