为什么在c++ 11中使用nullptr ?是什么?为什么NULL是不充分的?
c++专家Alex Allain在这里说得很好(我用粗体加了重点):
...imagine you have the following two function declarations:
void func(int n);
void func(char *s);
func( NULL ); // guess which function gets called?
Although it looks like the second function will be called--you are, after all, passing in what seems to be a pointer--it's really the first function that will be called! The trouble is that because NULL is 0, and 0 is an integer, the first version of func will be called instead. This is the kind of thing that, yes, doesn't happen all the time, but when it does happen, is extremely frustrating and confusing. If you didn't know the details of what is going on, it might well look like a compiler bug. A language feature that looks like a compiler bug is, well, not something you want.
Enter nullptr. In C++11, nullptr is a new keyword that can (and should!) be used to represent NULL pointers; in other words, wherever you were writing NULL before, you should use nullptr instead. It's no more clear to you, the programmer, (everyone knows what NULL means), but it's more explicit to the compiler, which will no longer see 0s everywhere being used to have special meaning when used as a pointer.
Allain在文章结尾写道:
不管这些——c++ 11的经验法则是,只要在过去使用NULL,就开始使用nullptr。
(我的话):
最后,不要忘记nullptr是一个对象——一个类。它可以在任何之前使用NULL的地方使用,但如果你因为某种原因需要它的类型,它的类型可以用decltype(nullptr)提取,或者直接描述为std::nullptr_t,这只是一个decltype(nullptr)的类型定义,如下所示:
定义在头<cstddef>:
See:
https://en.cppreference.com/w/cpp/types/nullptr_t
和https://en.cppreference.com/w/cpp/header/cstddef
namespace std
{
typedef decltype(nullptr) nullptr_t; // (since C++11)
// OR (same thing, but using the C++ keyword `using` instead of the C and C++
// keyword `typedef`):
using nullptr_t = decltype(nullptr); // (since C++11)
} // namespace std
引用:
c++ 11中更好的类型- nullptr,枚举类(强类型枚举)和cstdint
https://en.cppreference.com/w/cpp/language/decltype
https://en.cppreference.com/w/cpp/types/nullptr_t
https://en.cppreference.com/w/cpp/header/cstddef
https://en.cppreference.com/w/cpp/keyword/using
https://en.cppreference.com/w/cpp/keyword/typedef