Boost logo

Boost :

Subject: Re: [boost] Proposal: null pointer class
From: Simonson, Lucanus J (lucanus.j.simonson_at_[hidden])
Date: 2009-06-15 17:02:39


Martin Törnwall wrote:
> But a templated null pointer class also makes the code more clear, in
> my opinion. When passing null pointers as arguments to functions we
> can
> see, by merely looking at the call, what parameters the function
> expects
> to receive, which might give an indication of what it actually does.
>

Foo(0);
Foo(NULL);
Foo((char*)0);
Foo(reinterpret_cast<char*>(0));
Foo(null_ptr<char>());
Foo(null<char*>());

Of all of these only the first two are unclear. The rest are just different ways of doing (char*)0 by typing more. At best you are saving ten keystrokes over reinterpret_cast<char*>(0). Unless you do this quite a lot I don't think we'll ever save more keystrokes than we've spent discussing it, since I find myself passing by reference most of the time because people usually don't want to worry null pointers passed into their API. I think (char*)0 is perfectly fine because it is in no way ambiguous what it does. C-style casts for C-sytle types is my practice. For those who insist on typing more, do we really need a library solution? Please note that your library solution doesn't force people to use it to document their pointer type in the code, so it doesn't really solve this problem either, since people can forget to use it.

If you did this:

template <typename T> class cruel_ptr {
private:
  T* v;
  null_ptr(int); //not defined and illegal
public:
  null_ptr(T* t) v(t) {}
  operator T*() const { return v; }
};

then you could use it to prevent people from passing literal constant null values into your functions expecting a pointer type, but I'm not sure such would really be considered helpful by users of the API, and wouldn't solve the problem of legacy functions that take pointer arguments.

Regards,
Luke


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