nullptr and NULL

The CppCoreGuideline says: Use nullptr rather than 0 or NULL. The nullptr type introduced in C++11, it’s a pointer that can be used every object pointer. There is just one nullptr that can be used every pointer type whereas there are several NULL implementation.

Let’s use type traits to see what is what:

#include <iostream>
#include <type_traits>
std::cout << std::boolalpha;
std::cout << std::is_same<decltype(NULL), decltype(0)>::value << std::endl;
std::cout << std::is_same<decltype(NULL), decltype((void *)0)>::value << std::endl;
std::cout << std::is_same<decltype(NULL), std::nullptr_t>::value << std::endl;

Compilation results is same both on g++-6 and clang-8:

false
false
false

I was expecting the second one to be true then realise it doesn’t necessarily. Because NULL implementation not standard. To see what exactly it is, I head up to /usr/include and make a search:

NULL is just a number, a 0 casted to void * , and every library have its own implementation. This may cause some hard to find bugs.

void f(int i) { std::cout << "f(int) is called" << std::endl; }
f(0); 
f(NULL);

The first call is alright, an integer, but second one also will work! The NULL will be converted back to the 0. But the call to:

f(nullptr);

will cause compile time error.

error: no matching function for call to 'f'
        f(nullptr);

CC++

205 Words

2019-01-09 03:00 +0300