为什么在C ++中使用/是NULL? [英] Why was/is NULL used in C++?

查看:140
本文介绍了为什么在C ++中使用/是NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++标准将空指针定义为 0 。在很多代码中,我看到了 NULL 宏。

The C++ standard defines the null pointer to be 0. In a lot of code I've seen the NULL macro used however.

为什么会这样?如果标准定义 NULL 0 ,为什么要使用一个特殊的常数?

Why is it so? If the standard defines NULL to be 0 anyway, why use a special constant for it?

这只是一个美学的选择,还是有更实际的理由呢?或者,过去有没有一个理由不再有效,即从C ++标准的旧草稿保存?

Is it just an aesthetic choice, or is there a more practical reason for it? Or was there a reason in the past that is no longer valid, i.e. holdovers from older drafts of the C++ standard?

如何以及为什么 NULL

How and why did NULL begin to be used instead of 0?

推荐答案

开始使用

这是C的剩余部分, NULL 通常定义为(void *)0 。在C中,由于转换规则,它使 NULL 可隐式转换为任何其他指针类型,同时保持不可转换为整数类型:

This is a leftover from C, where NULL is often defined as (void*)0. In C, because of conversion rules, it makes NULL implicitly convertible to any other pointer type while remaining non convertible to integer types:

int* a = NULL; /* OK */
int b = NULL;  /* ERROR */

C ++没有这种宽松的类型转换,因此 NULL 在C ++中定义为 0 。虽然这意味着 int b = NULL; 是合法的,编译器通常是聪明的发出警告,如果这样做,因为他们认识到 NULL 是一个特殊的宏,因此保存了一些类型安全...当警告工作时。

C++ however does not have such loose type conversions, and therefore NULL is defined as 0 in C++. While this means that int b = NULL; is legal, compilers are generally smart enough to emit a warning if you do so as they recognized that NULL is a special macro thus preserving some of the type safety... when the warning works.

当然,在C ++ 11中,一个应该使用 nullptr 。在C ++ 03中,即使 Stroustrup 已经建议使用 0 ,而不是宏。

Of course, in C++11, one should use nullptr instead. In C++03 though even Stroustrup already recommended using 0 rather than a macro.

这篇关于为什么在C ++中使用/是NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆