I just read an article on the C++0x standard: http://www.softwarequalityconnection.com/2011/06/the-biggest-changes-in-c11-and-why-you-should-care/
It said nullptr
was strongly typed, meaning that it can be distinguished from an integer 0.
f(int);
f(char* p);
f(nullptr); // calls char* version
That's all good, but I'm interesting in knowing what the standard says about nullptr
with two pointer functions:
f(char* p);
f(int* p);
f(nullptr);
Do I need a cast here? And is nullptr
templated?
f((int*)(nullptr);
f(static_cast<int*>(nullptr));
f(nullptr<int>); // I would prefer this
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. Its values are null pointer constants (see NULL), and may be implicitly converted to any pointer and pointer to member type.
The nullptr keyword represents a null pointer value. Use a null pointer value to indicate that an object handle, interior pointer, or native pointer type does not point to an object.
nullptr vs NULL NULL is 0(zero) i.e. integer constant zero with C-style typecast to void*, while nullptr is prvalue of type nullptr_t which is integer literal evaluates to zero.
Another advantage (though admittedly minor) may be that nullptr has a well-defined numeric value whereas null pointer constants do not. A null pointer constant is converted to the null pointer of that type (whatever that is).
I haven't read the actual spec on this one, but I'm pretty sure that the call you indicated would be ambiguous without a cast, since a null pointer can be converted to a pointer of any type. So the cast should be necessary.
And no, unfortunately, nullptr
is not a template. I really like that idea, though, so you could consider writing a function like this one:
template <typename PtrType> PtrType null() {
return static_cast<PtrType>(nullptr);
}
And then you could write
f(null<int*>());
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