Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

nullptr

As far as I'm aware nullptr is a part of the core language.

Quoting C++11: (18.2/9)

nullptr_t is defined as follows:

namespace std { typedef decltype(nullptr) nullptr_t; }

and is defined in the header <cstddef>.

like image 808
embedc Avatar asked Aug 23 '19 14:08

embedc


Video Answer


3 Answers

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.

nullptr usurps the use of 0 to mean both a null pointer and, er, zero. Using 0 for both caused problems for obvious reasons, does f(0) call f(int) or f(int*)? So a brand new literal was added to the core language: nullptr. Its type is simply decltype(nullptr) so nullptr_t was added as a short cut:

namespace std {
    using nullptr_t = decltype(nullptr);
}
like image 112
Paul Evans Avatar answered Oct 17 '22 19:10

Paul Evans


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.

It also remarks, "We do not expect to see much direct use of nullptr_t in real programs". 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. In addition, if you don't want to include the header, you can always just write decltype(nullptr) yourself.

like image 41
Brian Bi Avatar answered Oct 17 '22 18:10

Brian Bi


From 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.

You can then solve overloaded function call ambiguity with 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

like image 1
Adrien Givry Avatar answered Oct 17 '22 19:10

Adrien Givry