本文介绍了使用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 over给它们赋值 NULL 0

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 see these overloaded functions:

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

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

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

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 problem, 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!!!







这篇关于使用nullptr有什么优点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 06:58