再谈NULL和nullptr(C++11)区别

2022-11-10,,,

在谈NULL和nullptr区别之前,我们先看段代码:

#include "stdafx.h"
#include <iostream> using namespace std;
void func(void *p)
{
cout << "p is pointer " << p << endl;
}
void func(int num)
{
cout << "num is int " << num << endl;
}
int main(void)
{
void *p = NULL;
func(p);
func(NULL);
func(nullptr); return 0;
}

大家猜猜执行结果是怎样的?

func(NULL)执行结果是 num is  int 0,

翻开NULL的定义,可以看到

C语言里面:

#define NULL ((void*)0)

​C++里面,它是这样定义的:​

#define NULL    0

查看完整的定义:

/* Define NULL pointer value */
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else /* __cplusplus */
#define NULL ((void *)0)
#endif /* __cplusplus */
#endif /* NULL */

​C语言我们用NULL作为指针变量的初始值,而在C++一般不建议这么做,C++中,如果想表示空指针,建议使用nullptr,而不是NULL。​

​NULL具有二义性,为了解决这种二义性,C++11标准引入了关键字nullptr作为空指针常量。​

我们开头的​代码function(nullptr)会调用func(void*),因为nullptr隐式转换为指针类型,而无法隐式转换为整形,编译器会找到形参为指针的函数版本。nullptr的出现消除了0带来的二义性,类型和含义更加明确。实际使用过程中,建议在编译器支持的前提下优先使用nullptr。​

再谈NULL和nullptr(C++11)区别的相关教程结束。

《再谈NULL和nullptr(C++11)区别.doc》

下载本文的Word格式文档,以方便收藏与打印。