简体   繁体   English

为什么nullptr是核心语言的一部分,但是nullptr_t是STL的一部分?

[英]Why is nullptr a part of the core language, but nullptr_t is a part of STL?

As far as I'm aware nullptr is a part of the core language. 据我所知, nullptr是核心语言的一部分。

Quoting C++11: (18.2/9) 引用C ++ 11:(18.2 / 9)

nullptr_t is defined as follows: nullptr_t定义如下:

namespace std { typedef decltype(nullptr) nullptr_t; }

and is defined in the header <cstddef> . 并在标题<cstddef>定义。

Because it can. 因为它可以。 A central aim in the C++ standardization process is to alter the core language as little as possible when adding to the language. C ++标准化过程的核心目标是在添加语言时尽可能少地改变核心语言。

nullptr usurps the use of 0 to mean both a null pointer and, er, zero. nullptr篡改使用0来表示空指针和呃,零。 Using 0 for both caused problems for obvious reasons, does f(0) call f(int) or f(int*) ? 由于显而易见的原因,使用0导致两个问题, f(0)调用f(int)f(int*) So a brand new literal was added to the core language: nullptr . 因此,核心语言中添加了一个全新的文字: nullptr Its type is simply decltype(nullptr) so nullptr_t was added as a short cut: 它的类型只是decltype(nullptr)所以nullptr_t被添加为捷径:

namespace std {
    using nullptr_t = decltype(nullptr);
}

The proposal that introduced nullptr , N2431 , indicates in section 1.1 that it was desirable to not force users to include a header in order to use nullptr . 引入nullptr的提议N2431在1.1节中指出,为了使用nullptr ,最好不要强制用户包含头。

It also remarks, "We do not expect to see much direct use of nullptr_t in real programs". 它还评论说,“我们不希望看到在实际程序中直接使用nullptr_t ”。 Thus, it was considered preferable to add nullptr_t to the library rather than create a new keyword only to be used for this obscure purpose. 因此,最好将nullptr_t添加到库中,而不是创建一个新的关键字,仅用于这个模糊的目的。 In addition, if you don't want to include the header, you can always just write decltype(nullptr) yourself. 此外,如果您不想包含标题,您可以随时自己编写decltype(nullptr)

From cppreference.com: 来自cppreference.com:

std::nullptr_t is the type of the null pointer literal , nullptr. std :: nullptr_t是空指针文字类型 ,nullptr。 It is a distinct type that is not itself a pointer type or a pointer to member type. 它是一种独特的类型,它本身不是指针类型或指向成员类型的指针。

If two or more overloads accept different pointer types, an overload for std::nullptr_t is necessary to accept a null pointer argument . 如果两个或多个重载接受不同的指针类型, 则需要std :: nullptr_t的重载来接受空指针参数

You can then solve overloaded function call ambiguity with std::nullptr_t . 然后,您可以使用std::nullptr_t解决重载函数调用歧义。

For example: 例如:

void Foo(int* ptr) {}
void Foo(double* ptr) {}
void Foo(std::nullptr_t ptr) {} // This overload is called if Foo(nullptr) is invoked

Read more about std::nullptr_t here: https://en.cppreference.com/w/cpp/types/nullptr_t 在这里阅读更多关于std::nullptr_t信息: https std::nullptr_t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM