什么是nullptr? [英] What exactly is nullptr?

查看:606
本文介绍了什么是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

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。

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 c $ c> 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 类型的指针文字,它是一个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 type std::nullptr_t is a null pointer constant, and that an integral null pointer constant can be converted to std::nullptr_t. The opposite direction is not allowed. This allows overloading a function for both pointers and integers, and passing nullptr to select the pointer version. Passing NULL or 0 would confusingly select the int 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆