[英]Where and why is std::nullptr_t in the std namespace?
Firstly, std::nullptr_t
is a core language type, so why is it in the std
namespace?首先,
std::nullptr_t
是一种核心语言类型,为什么它在std
命名空间中? You don't see std::char
or std::int
.您看不到
std::char
或std::int
。
Secondly, where is it in the std
namespace?其次,它在
std
命名空间中的什么位置? When I right click in Visual Studio to see where it is declared, it says "the symbol nullptr_t is not located in any source file."当我在 Visual Studio 中右键单击以查看它的声明位置时,它显示“符号 nullptr_t 不在任何源文件中”。 If
std::nullptr_t
is not declared in the std
namespace, why does code containing std::nullptr_t
compile?如果
std::nullptr_t
没有在std
命名空间中声明,为什么包含std::nullptr_t
的代码可以编译?
EDIT: This link on microsoft's website says nullptr is a built in type, and that built in types are not defined in header files.编辑:微软网站上的这个链接说 nullptr 是一个内置类型,内置类型没有在 header 文件中定义。
std::nullptr_t is a core language type
std::nullptr_t 是一种核心语言类型
No, it is not a core language type.不,它不是核心语言类型。 In fact, it is not even a pointer type though it can be implicitly converted to any pointer type.
事实上,它甚至不是指针类型,尽管它可以隐式转换为任何指针类型。 Moreover, it is defined inside header
cstddef
in namepsace std
as quoted below.此外,它在 namepsace
std
中的 header cstddef
内部定义,如下所述。
This can be seen from lex.nullptr :这可以从lex.nullptr看出:
The pointer literal is the keyword
nullptr
.指针文字是关键字
nullptr
。 It is a prvalue of typestd::nullptr_t
.它是
std::nullptr_t
类型的纯右值。 [ Note:std::nullptr_t
is a distinct type that is neither a pointer type nor a pointer-to-member type ;[注意:
std::nullptr_t
是一种独特的类型,既不是指针类型也不是指向成员的指针类型; rather, a prvalue of this type is a null pointer constant and can be converted to a null pointer value or null member pointer value.相反,此类型的纯右值是 null 指针常量,可以转换为 null 指针值或 null 成员指针值。 See [conv.ptr] and [conv.mem].
参见 [conv.ptr] 和 [conv.mem]。 — end note ]
——尾注]
From cstddef.syn :来自cstddef.syn :
Header
<cstddef>
synopsisHeader
<cstddef>
概要namespace std { using nullptr_t = decltype(nullptr); //other things here }
In both libstdc++, libc++, and MSVC's STL, std::nullptr_t
is a typedef for decltype(nullptr)
.在 libstdc++、libc++ 和 MSVC 的 STL 中,
std::nullptr_t
是decltype(nullptr)
的类型定义。
So yes, the type is a core language type, but it doesn't have a name, and the only way to refer to it (without the header) is with decltype(nullptr)
.所以是的,该类型是一种核心语言类型,但它没有名称,唯一引用它的方法(没有标题)是使用
decltype(nullptr)
。
As others have stated, std::nullptr_t
is a special type .正如其他人所说,
std::nullptr_t
是一种特殊类型。 It is to be distinguished from nullptr
itself - which is a value .它与
nullptr
本身区别开来——后者是一个值。
There are some use cases for std::nullptr_t
. std::nullptr_t
有一些用例。
For example function overloads:例如 function 重载:
void foo(int*);
void foo(nullptr_t);
int main() {
int a = 4;
int* b = &a;
foo(b); // will call foo(int*)
foo(nullptr); // will call foo(nullptr_t)
b = nullptr;
foo(b); // will call foo(int*)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.