Boost logo

Boost :

Subject: [boost] Proposal: null pointer class
From: Martin Törnwall (herede_at_[hidden])
Date: 2009-06-15 10:58:45


Hello Boost developers,

I'd like to propose the inclusion of a null_ptr class in Boost. While I
am fully aware that this topic has been brought up several times in the
past, it appears as if though all discussions slowly died off without
any final decision as to whether it is a worthy candidate for inclusion
in Boost or not.

The null pointer class proposals I have seen before were all designed to
function in a manner similar to that of the "nullptr" keyword of C++0x.
That is, the classes typically provided a template conversion operator,
which allows it to evaluate to any pointer type with the value zero. My
approach is to make the class, rather than the operator, a template:

template<typename T> class null_ptr
{
public:
   operator T*() const
   {
       return reinterpret_cast<T *>(0);
   }
};

As we can see, passing a null_ptr requires us to explicitly specify the
type of pointer. While slightly verbose, I believe that it can be highly
beneficial, for the following reasons:
1. In cases where multiple overloaded functions that take pointers
exist, there is no way that we could accidentally call the wrong
overload (since we have to explicity specify the type).
2. It makes code easier to read and understand. When reading the code,
another programmer will instantly be able to see what type argument(s) a
particular function accepts, thus making it much clearer than using NULL
or nullptr.

As with all other null pointer classes that have been suggested to date,
the primary benefit of using my null_ptr over the NULL constant is that
it solves the following problem:

void f(int)
{
   ...
}

void f(char *)
{
   ...
}

int main()
{
   func(NULL);
   func(null_ptr<char>());
}

When passing NULL, f(int) will be called -- probably not what the
programmer intended. The second call utilizes null_ptr<char> to
guarantee that the overload of f() taking char* will be called instead
of the one taking int. As noted above, my null_ptr class also handles
multiple overloads taking pointer types gracefully. Please let me know
what you think!

P.S: I have tested the code on Microsoft Visual C++ 2008 as well as gcc
4.3.3 (Linux).

Regards,
Martin Törnwall


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk