Why not use 'nullptr'?

Due to the book "Effective Modern C++", modern C++ programmers should prefer nullptr to 0 and NULL. The reason is that 0 or NULL is neither a pointer type. Suppose we have a function

void foo(int);
void foo(bool);
void foo(void*);

If we call it like foo(0) or foo(NULL), we will get foo(int) called instead of foo(void*). Why? Because 0 and NULL are never pointer type, 0 is 'int' and NULL can be 'long'. So use 'nullptr', it has a type of 'std::nullptr_t' and can be implicitly converted to all raw pointer types.

Another concern is that suppose we'd like to write a template function

class Class1, Class2;

int foo(std::shared_ptr<Class1> sth);
float bar(std::unique_ptr<Class2> sth);

template<typename FuncType, typename PtrType>
decltype(auto) callSth(FuncType func, PtrType ptr) {
    return func(ptr);
}

Then if we write

auto a = callSth(foo, 0);
auto b = callSth(bar, NULL);

both would fail during compilation since it's a type error. 0 or NULL is not compatible with the function type as declared.

Leave a Reply

Your email address will not be published. Required fields are marked *