问题描述
我们现在有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
。
int* x = nullptr;
myclass* obj = nullptr;
我还是没有得到 nullptr
作品。例如,说:
Still, I am not getting how nullptr
works. For example, Wikipedia article says:
C ++ 11通过引入一个新的关键字来纠正这种情况,以作为一个区分的空指针常量:nullptr。它是类型nullptr_t ,它是隐式可转换的,并可与任何指针类型或指针成员类型相比。它不是隐式可转换的或可比的整数类型,除了bool。
它是一个关键字和一个类型的实例?
How is it a keyword and an instance of a type?
此外,还有另一个例子(维基百科旁边),其中 nullptr
c $ c> 0 ?
Also, do you have another example (beside the Wikipedia one) where nullptr
is superior to good old 0
?
推荐答案
这并不奇怪。 true
和 false
是关键字和文字,它们有一个类型( bool
)。 nullptr
是 std :: nullptr_t
类型的指针文字,它是一个prvalue你不能使用&
)的地址。关于指针转换的
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
c $ c> 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
的转换相同的语义。 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)
)
The Standard requires that
sizeof(nullptr_t)
be sizeof(void*)
.
这篇关于什么是nullptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!