nullptr 究竟是什么? [英] What exactly is nullptr?
问题描述
我们现在拥有具有许多新功能的 C++11.一个有趣且令人困惑的(至少对我而言)是新的 nullptr
.
We now have C++11 with many new features. An interesting and confusing one (at least for me) is the new nullptr
.
好吧,不再需要讨厌的宏 NULL
.
Well, no need anymore for the nasty macro NULL
.
int* x = nullptr;
myclass* obj = nullptr;
仍然,我不明白 nullptr
是如何工作的.例如,维基百科文章说:
Still, I am not getting how nullptr
works. For example, Wikipedia article says:
C++11 通过引入一个新的关键字来纠正这个问题,作为一个特殊的空指针常量:nullptr.它是 type nullptr_t,可以隐式转换,并且可以与任何指针类型或指向成员的指针类型相比较.除了 bool 之外,它不能隐式转换或与整型比较.
C++11 corrects this by introducing a new keyword to serve as a distinguished null pointer constant: nullptr. It is of type nullptr_t, which is implicitly convertible and comparable to any pointer type or pointer-to-member type. It is not implicitly convertible or comparable to integral types, except for bool.
关键字和类型的实例如何?
How is it a keyword and an instance of a type?
另外,你有没有另一个例子(除了维基百科的那个),其中 nullptr
优于旧的 0
?
Also, do you have another example (beside the Wikipedia one) where nullptr
is superior to good old 0
?
推荐答案
关键字和类型的实例如何?
How is it a keyword and an instance of a type?
这并不奇怪.true
和 false
都是关键字,作为文字,它们有一个类型( bool
).nullptr
是 std::nullptr_t
类型的指针文字,它是一个纯右值(你不能使用 &
).
This isn't surprising. Both true
and false
are keywords and as literals they have a type ( bool
). nullptr
is a pointer literal of type std::nullptr_t
, and it's a prvalue (you cannot take the address of it using &
).
4.10
关于指针转换说std::nullptr_t
类型的纯右值是空指针常量,可以转换整型空指针常量到std::nullptr_t
.不允许相反方向.这允许为指针和整数重载函数,并传递nullptr
以选择指针版本.传递NULL
或0
会混淆选择int
版本.
4.10
about pointer conversion says that a prvalue of typestd::nullptr_t
is a null pointer constant, and that an integral null pointer constant can be converted tostd::nullptr_t
. The opposite direction is not allowed. This allows overloading a function for both pointers and integers, and passingnullptr
to select the pointer version. PassingNULL
or0
would confusingly select theint
version.
nullptr_t
到整数类型的转换需要一个 reinterpret_cast
,并且与 (void*)0<的转换具有相同的语义/code> 到整数类型(定义映射实现).
reinterpret_cast
不能将 nullptr_t
转换为任何指针类型.如果可能,依靠隐式转换或使用 static_cast
.
A cast of nullptr_t
to an integral type needs a reinterpret_cast
, and has the same semantics as a cast of (void*)0
to an integral type (mapping implementation defined). A reinterpret_cast
cannot convert nullptr_t
to any pointer type. Rely on the implicit conversion if possible or use static_cast
.
标准要求 sizeof(nullptr_t)
为 sizeof(void*)
.
这篇关于nullptr 究竟是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!