使用 nullptr 有什么好处?

2022-01-06 00:00:00 null c++ c++11 c++-faq nullptr

这段代码概念上对三个指针做了同样的事情(安全指针初始化):

This piece of code conceptually does the same thing for the three pointers (safe pointer initialization):

int* p1 = nullptr;
int* p2 = NULL;
int* p3 = 0;

那么,分配指针 nullptr 与分配值 NULL0 相比有什么优势?

And so, what are the advantages of assigning pointers nullptr over assigning them the values NULL or 0?

推荐答案

在那段代码中,似乎没有什么优势.但请考虑以下重载函数:

In that code, there doesn't seem to be an advantage. But consider the following overloaded functions:

void f(char const *ptr);
void f(int v);

f(NULL);  //which function will be called?

会调用哪个函数?当然,这里的意图是调用f(char const *),但实际上会调用f(int)!这是个大问题1,不是吗?

Which function will be called? Of course, the intention here is to call f(char const *), but in reality f(int) will be called! That is a big problem1, isn't it?

所以,解决此类问题的方法是使用nullptr:

So, the solution to such problems is to use nullptr:

f(nullptr); //first function is called

<小时>

当然,这不是 nullptr 的唯一优势.这是另一个:


Of course, that is not the only advantage of nullptr. Here is another:

template<typename T, T *ptr>
struct something{};                     //primary template

template<>
struct something<nullptr_t, nullptr>{};  //partial specialization for nullptr

由于在模板中,nullptr的类型被推导出为nullptr_t,所以你可以这样写:

Since in template, the type of nullptr is deduced as nullptr_t, so you can write this:

template<typename T>
void f(T *ptr);   //function to handle non-nullptr argument

void f(nullptr_t); //an overload to handle nullptr argument!!!

<小时>

1.在C++中,NULL被定义为#define NULL 0,所以基本上是int,这就是为什么f(int) 被调用.


1. In C++, NULL is defined as #define NULL 0, so it is basically int, that is why f(int) is called.

相关文章