在 C++ 的早期,当它被栓在 C 之上时,您不能使用 NULL,因为它被定义为 (void*)0
.除了 void*
之外,您不能将 NULL 分配给任何指针,这使它变得毫无用处.在那些日子里,您使用 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++ 风格和技术常见问题解答
Here's Stroustrup's take on this: C++ Style and Technique FAQ
在 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 withNULL
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(零)作为指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!