你在C ++中使用NULL或0(零)指针吗? [英] Do you use NULL or 0 (zero) for pointers in C++?

查看:125
本文介绍了你在C ++中使用NULL或0(零)指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++的早期,当它被固定在C的顶部时,你不能使用NULL,因为它被定义为(void *)0 。你不能将NULL赋给 void * 之外的任何指针,这使它无用。回到那些日子,我们接受了你使用 0 (零)的空指针。

In the early days of C++ when it was bolted on top of C, you could not use NULL as it was defined as (void*)0. You could not assign NULL to any pointer other than void*, which made it kind of useless. Back in those days, it was accepted that you used 0 (zero) for null pointers.

,我继续使用零作为一个空指针,但我周围的人坚持使用 NULL 。我个人没有看到任何好处给一个名字( NULL )到现有的值 - 并且因为我也喜欢测试指针作为真值:

To this day, I have continued to use zero as a null pointer but those around me insist on using NULL. I personally do not see any benefit to giving a name (NULL) to an existing value - and since I also like to test pointers as truth values:

if (p && !q)
  do_something();

然后使用零更有意义(如果你使用 NULL ,你不能在逻辑上使用 p&&&q; - 你需要显式比较 NULL ,除非你假设 NULL 为零,为什么使用 NULL )。

then using zero makes more sense (as in if you use NULL, you cannot logically use p && !q - you need to explicitly compare against NULL, unless you assume NULL is zero, in which case why use NULL).

有没有任何客观的理由偏好零超过NULL(或反之亦然),还是只是个人偏好?

Is there any objective reason to prefer zero over NULL (or vice versa), or is all just personal preference?

编辑:添加(原来是说)有RAII和异常,我很少使用零/ NULL指针,但有时你确实需要它们。

I should add (and meant to originally say) that with RAII and exceptions, I rarely use zero/NULL pointers, but sometimes you do need them still.

推荐答案

这里是Stroustrup对此的介绍: C ++风格和技巧常见问题


在C ++中, NULL 的定义为0,因此只有美学上的差异。我喜欢避免宏,所以我使用0. NULL 的另一个问题是人们有时会错误地认为它不同于0和/或不是一个整数。在预标准代码中, NULL 有时被定义为不适合的,因此必须避免。

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.

如果你必须命名空指针,调用 nullptr ;这就是它在C ++ 11中调用。然后, nullptr 将是一个关键字。

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.

也就是说,不要冒出小东西。

That said, don't sweat the small stuff.

这篇关于你在C ++中使用NULL或0(零)指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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