nullptr
is a keyword that denotes the pointer literal with the unique std::nullptr_t
type.
It’s convertible to a null pointer value of any pointer
type or any pointer to member
type:
#include <iostream>using namespace std;struct MyStruct { };void pointer_to_fundamental_type(int* ptr) {std::cout << "Hello from void pointer_to_fundamental_type(int*)\n";}void pointer_to_user_defined_type(MyStruct* ptr) {std::cout << "Hello from void pointer_to_user_defined_type(MyStruct*)\n";}// Accepts pointer to member of MyStruct that has// int typevoid pointer_to_member_object(int MyStruct::*) {std::cout << "Hello from void pointer_to_member_object(int MyStruct::*)\n";}// Accepts pointer to member function of MyStruct// that has int return type and no argumentsvoid pointer_to_member_function(int (MyStruct::*)(void)) {std::cout << "Hello from pointer_to_member_function(int (MyStruct::*)(void))\n";}int main() {std::nullptr_t null = nullptr;// nullptr is convertible to null pointer of// any pointer type:pointer_to_fundamental_type(nullptr);pointer_to_user_defined_type(null);// and any pointer to member type:pointer_to_member_object(nullptr);pointer_to_member_function(null);}
#include <cstddef> // contains NULL pointer constant definition#include <iostream>template<class T>constexpr T clone(const T& t){return t; // Return copy of t}void g(int*){std::cout << "Function g called\n";}int main(){g(nullptr); // Fineg(NULL); // Fineg(0); // Fineg(clone(nullptr)); // Fine// g(clone(NULL)); // ERROR: invalid conversion from ‘long int’ to ‘int*’// g(clone(0)); // ERROR: invalid conversion from ‘int’ to ‘int*’int* ptr = nullptr; // Fineint* null_ptr = NULL; // Fineint* zero_ptr = 0; // Fineint* clone_ptr = clone(nullptr); // Fine// int* clone_null_ptr = clone(NULL); // error: error: invalid conversion from ‘long int’ to ‘int*’// int* clone_zero_ptr = clone(0); // error: invalid conversion from `int` to `int*`}