failing constructors

From: Tomas Frydrych <tomasfrydrych_at_yahoo.co.uk>
Date: Tue Oct 12 2004 - 09:32:24 CEST

The real problem with constructors is not that new might fail, but
that while new itself succeeds the object it creates is in fact
invalid (because of non-fatal failure of the constructor); the
GR_Win32Font object is an example where this is a real possibility.

While exceptions make this scenario simple to handle, it can be
worked around quite easily without them by making the constructor in
question private/protected and providing a static wrapper
construction method, which can verify the validity of the object and
translate constructor failure into NULL, something like:

class object
{
  private:
    object();

  public:
    bool isValid() { // some tests ...}
    static object * new_object()
    {
       object * p = new object();
       if(p && !p->isValid())
       {
          delete p;
          return NULL;
       }
       return p;
    }
};

I am planing to add static methods GR_Win32Font::newFont() and
GR_Win32USPFont::newFont() and made both constructors protected; this
will allow me to remove all the exception code -- I hope this
solution is satisfactory.

Tomas
Received on Tue Oct 12 09:32:22 2004

This archive was generated by hypermail 2.1.8 : Tue Oct 12 2004 - 09:32:22 CEST