使用 nullptr 有什么好处?

2023-12-02C/C++开发问题
4

本文介绍了使用 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.

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

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6