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?
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With