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

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

据我所知nullptr是核心语言的一部分。

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

nullptr_t is defined as follows:

namespace std { typedef decltype(nullptr) nullptr_t; }

并定义在header <cstddef>.

因为可以。 C++ 标准化过程的一个中心目标是在向语言添加内容时尽可能少地改变核心语言。

nullptr 篡夺了 0 的用法来表示空指针和,呃,零。由于显而易见的原因,对这两个问题都使用 0f(0) 调用 f(int) 还是 f(int*)?于是在核心语言中加入了一个全新的字面量:nullptr。它的类型只是 decltype(nullptr) 所以 nullptr_t 被添加为一个快捷方式:

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

来自 cppreference.com:

std::nullptr_t is the type of the null pointer literal, 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.

解决重载函数调用的歧义

例如:

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

在此处阅读有关 std::nullptr_t 的更多信息:https://en.cppreference.com/w/cpp/types/nullptr_t

引入 nullptrN2431 的提案在第 1.1 节中指出,最好不要强迫用户包含 header 以便使用 nullptr .

它还表示,"We do not expect to see much direct use of nullptr_t in real programs"。因此,将 nullptr_t 添加到库中被认为比创建一个仅用于此模糊目的的新关键字更可取。此外,如果您不想包含 header,您可以随时自己编写 decltype(nullptr)