前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >关于nullptr这篇文章你一定要看

关于nullptr这篇文章你一定要看

作者头像
用户6280468
发布2022-03-21 16:51:01
4920
发布2022-03-21 16:51:01
举报
文章被收录于专栏:txp玩Linuxtxp玩Linux

众所周知C++ 11引入了nullptr,关于C++11新特性,可以看我之前的文章《c++11新特性,所有知识点都在这了!》。nullptr使用代码如下:

代码语言:javascript
复制
int *ptr = nullptr;

同样是表示空指针,之前NULL使用的好好的,为什么要引入nullptr?

nullptr和NULL又有什么区别呢?

NULL究竟是什么?

源码在此:

代码语言:javascript
复制
#ifndef NULL
    #ifdef __cplusplus
        #define NULL 0
    #else
        #define NULL ((void *)0)
    #endif
#endif

从源码中可以知道,在C中NULL是((void *)0)指针,在C++中NULL却是个整数0。

为什么同样是NULL,在C和C++中却有不同的定义呢?

C++中有一个很特别的规定就是0既表示整形常量也用来表示空指针常量

先看下C++03标准中的一段话:

A null pointer constant is an integral constant expression (expr.const) rvalue of integer type that evaluates to zero. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of pointer to object or pointer to function type. Two null pointer values of the same type shall compare equal. The conversion of a null pointer constant to a pointer to cv-qualified type is a single conversion, and not the sequence of a pointer conversion followed by a qualification conversion (conv.qual).

主要规定空指针常量需要被转化成指针类型,同时这个转化为指针类型的值还不能和其它的对象指针或者函数指针的值相同。两个空指针常量的值还需要相等。

而C99标准中说:

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.[55] If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

主要就是说C中的空指针常量是整型0被强转成了void*,这就可以确保这个空指针的值与其它对象或函数指针值不相等。

这里C++中的NULL如果和C语言一样也是(void *)0指针,而C++却又不允许void*隐式转换成其它指针类型,那还怎么用NULL来表示空指针呢,岂不是尴尬了。

下面代码编译会报错:

代码语言:javascript
复制
#include <iostream>

int main() {
    int *a = (void *)0;
    return 0;
}
error: cannot initialize a variable of type 'int *' with an rvalue of type 'void *'

为什么要引入nullptr?

一个原因是可以让整形0放下重担,0只表示一件事情,它只是一个整数类型0,没有任何其它语义,空指针的活就安排给其它员工,这个员工就是nullptr关键字。

先看一段代码:

代码语言:javascript
复制
void func(char*) {
    cout << "char*";
}
void func(int) {
    cout << "int";
}

int main() {
     func(NULL); // 编译失败 error: call of overloaded ‘func(NULL)’ is ambiguous
    func(nullptr); // char*
    return 0;
}

另一个原因是在C++的函数重载中,传入NULL会导致编译失败,所以需要引入nullptr,使用nullptr可以解决函数重载中的参数匹配问题。

这里可以总结三点:

1、使用nullptr可以不用担心整型和指针类型的重载,不会产生二义性导致编译失败。

2、0和空指针分别表示不同的含义,使用nullptr可以更好的支持模板编程。

3、使用nullptr使代码更安全,让用户编写代码更清晰直观。

代码语言:javascript
复制
if (ptr == nullptr) {}
if (ptr == NULL) {}
if (ptr == 0) {}

三种方式哪个更好?相信你已经有答案了吧!

让我们看看大佬怎么说的(摘自C++之父语录):

Should I use NULL or 0?

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.

NULL其实就是一个宏,对于宏,C++之父一直推崇尽量避免使用它,在实际编程中,可以减少宏的使用,直接使用0。Bjarne Stroustrup语录也给出了解释。所以在C++中,完全可以抛弃掉NULL,不得已可以使用0替代。

既然NULL就是0,那为什么不直接使用0,而搞出来一个NULL呢?

因为需要为空指针常量起一个名字,更清晰的表明它表达的是什么含义,就像3.1415926为什么要用π表示一样,尽管宏一直是被各方吐槽的,但为了有名字在当时C++也只能这样,这也是NULL宏面世的唯一一个理由。

所以如果编译器支持nullptr,一定要使用nullptr。

空指针应该有什么特性吗?

1. 它应该有一个自己的名字,它应该是一个保留关键字。

2. 空指针不能够被用于算数表达式中,不能被赋值给整型,也不能用于和指针类型外的类型做比较。

3. 空指针可以被转化成任何指针类型,不能被转换成指针类型外的任何类型。

你有没有想过,nullptr为什么可以转换成int*, float*等?

看下它可能的实现吧:

代码语言:javascript
复制
struct nullptr_t
{
    void operator&() const = delete;  // Can't take address of nullptr

    template <class T>
    inline operator T*() const
    {
        return 0;
    }

    template <class C, class T>
    inline operator T C::*() const
    {
        return 0;
    }
};

nullptr_t nullptr;

通过实现了部分运算符,所以nullptr可以转换成int*等,同时,为什么不能对nullptr取址?因为它的取址操作被delete修饰了。

使用nullptr还有什么好处呢?可以用于抛出异常。

nullptr是有类型的:

代码语言:javascript
复制
typdef decltype(nullptr) nullptr_t;

当空指针用nullptr表示时,空指针就终于有类型了,当有异常需要抛出时,就可以抛出nullptr。

代码语言:javascript
复制
int main() {
    try {
        ...
        throw nullptr;
    } catch(nullptr_t) {
        ...
    }
}

之后使用它的类型nullptr_t捕获,这里如果throw NULL,那用什么类型去catch呢?用int类型来catch?是不是有点别扭。所以能用nullptr就一定要用nullptr代替NULL。

关于nullptr的介绍就到这里,希望大家会有所收获~

参考资料

https://www.cnblogs.com/DswCnblog/p/5629073.html

https://www.stroustrup.com/bs_faq2.html#null

https://dzone.com/articles/what-exactly-nullptr-is-in-c

https://www.zhihu.com/question/22203461

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2431.pdf

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-10-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 txp玩Linux 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档