Boost logo

Boost Users :

From: Douglas Gregor (gregod_at_[hidden])
Date: 2002-09-10 10:09:28


On Tuesday 10 September 2002 10:56 am, Bertolt Mildner wrote:
> Is really only a valid (member) function pointer guaranteed to be non-null?
> I think it is very strange that ~0 may not be non-null!

Yes, it is strange, but it should be possible. For instance, this isn't
guaranteed to give a null function pointer:

  int x = 1;
  return (safe_bool)(1-x);

Only an integral constant expression that is '0', when converted to a pointer,
is guaranteed to become the null pointer. You also can't rely on:

  T* p = 0;
  int p_int = (int)p;
 assert(p_int == 0); // p_int need not be zero!

Except for the syntactic oddity that '0' can be converted to a null pointer,
there need not be a relationship between an integer 0 and the null pointer :)

> I have tried this one:
> > typedef void (*safe_bool)();

You don't want to do that :) safe_bool is a pointer-to-member-function so that
it is _only_ useful in boolean contexts. Perhaps this would appease your
compiler:

  struct dummy {
    template<typename T> void nonnull() {};
  };

  typedef void (dummy::*safe_bool)();

  operator safe_bool () const
    { return (this->empty())? 0 : &dummy::nonnull<int>; }

  safe_bool operator!() const
    { return (!this->empty())? 0 : &dummy::nonnull<int>; }

If it works, I'll put the workaround into CVS.

        Doug


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net