C++ NULL 与 nullptr(为什么被替换?)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20509734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NULL vs nullptr (Why was it replaced?)
提问by Riptyde4
I know that in C++ 0x
or NULL
was replaced by nullptr
in pointer-based applications. I'm just curious of the exact reason why they made this replacement?
我知道在 C++ 中0x
或在基于指针的应用程序中NULL
被替换nullptr
。我只是很好奇他们做出这个替代品的确切原因?
In what scenario is using nullptr
over NULL
beneficial when dealing with pointers?
在处理指针时在什么情况下使用nullptr
overNULL
有益?
回答by Joe Z
nullptr
is always a pointer type. 0
(aka. C's NULL bridged over into C++) could cause ambiguity in overloaded function resolution, among other things:
nullptr
始终是指针类型。 0
(又名。C 的 NULL 桥接到 C++)可能导致重载函数解析中的歧义,其中包括:
f(int);
f(foo *);
回答by Shafik Yaghmour
You can find a good explanation of why it was replaced by reading A name for the null pointer: nullptr, to quote the paper:
您可以通过阅读空指针的名称:nullptr来引用论文,找到有关为什么它被替换的很好的解释:
This problem falls into the following categories:
Improve support for library building, by providing a way for users to write less ambiguous code, so that over time library writers will not need to worry about overloading on integral and pointer types.
Improve support for generic programming, by making it easier to express both integer 0 and nullptr unambiguously.
Make C++ easier to teach and learn.
这个问题分为以下几类:
改进对库构建的支持,为用户提供一种编写不那么模棱两可的代码的方法,以便库编写者随着时间的推移无需担心整数和指针类型的重载。
通过更容易地明确表达整数 0 和 nullptr 来改进对泛型编程的支持。
让 C++ 更容易教和学。
回答by Deidrei
Here is Bjarne Stroustrup's wordings,
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.
在 C++ 中,NULL 的定义是 0,所以只有审美差异。我更喜欢避免使用宏,所以我使用 0。NULL 的另一个问题是人们有时会错误地认为它不同于 0 和/或不是整数。在标准前的代码中,NULL 有时被/被定义为不合适的东西,因此必须/必须避免。这几天不太常见。
如果必须命名空指针,则称其为 nullptr;这就是它在 C++11 中的名称。然后,“nullptr”将是一个关键字。
回答by Cheers and hth. - Alf
One reason: the literal 0
has a bad tendency to acquire the type int
, e.g. in perfect argument forwarding or more in general as argument with templated type.
一个原因:文字0
有一个不好的倾向来获取类型int
,例如在完美的参数转发中或更一般地作为模板类型的参数。
Another reason: readability and clarity of code.
另一个原因:代码的可读性和清晰度。