Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I use nullptr without including STL?

The C++ nullptr is of the type std::nullptr_t.

Why does a program like

int main() {
 int* ptr = nullptr;
}

still work, although it doesn't include any STL library?

like image 453
Robert Hönig Avatar asked Aug 22 '16 13:08

Robert Hönig


People also ask

Can I use nullptr instead of null?

nullptr is a keyword that can be used at all places where NULL is expected. Like NULL, nullptr is implicitly convertible and comparable to any pointer type. Unlike NULL, it is not implicitly convertible or comparable to integral types.

Why do we use nullptr in C++?

The nullptr keyword can be used to test if a pointer or handle reference is null before the reference is used. Function calls among languages that use null pointer values for error checking should be interpreted correctly. You cannot initialize a handle to zero; only nullptr can be used.

What happens if you delete a nullptr?

In c++03 it is pretty clear that deleting a null pointer has no effect. Indeed, it is explicitly stated in §5.3. 5/2 that: In either alternative, if the value of the operand of delete is the null pointer the operation has no effect.

What library is nullptr in?

The C library Macro NULL is the value of a null pointer constant. It may be defined as ((void*)0), 0 or 0L depending on the compiler vendor.


1 Answers

In C++11 they wanted to add a keyword to replace the macro NULL (which is basically defined as #define NULL 0), both because it is a core concept, and because of some annoying bugs you get when you are forced to use 0 as your null pointer constant.

A number of keywords where proposed. Large codebases where searched to ensure that the keyword was not in use, and that it still described what they wanted (a null pointer constant).

nullptr was found to be sufficiently rare and evocative enough.

The type of nullptr was not given a keyword name by default, because that wasn't required for most programs. You can get it via decltype(nullptr) or including a std header and using std::nullptr_t.

like image 178
Yakk - Adam Nevraumont Avatar answered Oct 15 '22 06:10

Yakk - Adam Nevraumont