home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!mcsun!sunic!hagbard!loglule!jbn
- From: jbn@lulea.trab.se (Johan Bengtsson)
- Newsgroups: comp.lang.c++
- Subject: Re: question on REFERENCES
- Message-ID: <5233@holden.lulea.trab.se>
- Date: 18 Nov 92 13:22:34 GMT
- References: <1992Nov18.003803.29938@fcom.cc.utah.edu>
- Organization: Telia Research AB, Aurorum 6, 951 75 Lulea, Sweden
- Lines: 40
- X-Newsreader: Tin 1.1 PL4
-
- swillden@news.ccutah.edu (Shawn Willden) writes:
- : kestes@nswc-wo.nswc.navy.mil (Kent Estes) writes:
- : :
- : : I am working on a function that references objects via id. Upon finding
- : : an object, it returns a reference to that object. My question is :
- : : if the object is not found, what is the best way to handle this. If
- : : I were returning pointers to objects, all I would have to do is
- : : return NULL.
- :
- : So return a pointer. There is no way to return a NULL reference (which
- : is good, if you have a reference you *know* that it refers to something).
- :
- : If there really is a good reason why you need to return a reference
- : instead of a pointer you can declare a special object of the return
- : type that is always to be returned in case of error and then compare
- : the address of the returned object with the address of the error
- : object (or overload operator== and play games with that). Usually,
- : though, you're better off just returning a pointer.
-
- I disagree. The described scheme requires the user to test
- the result of every function call that may fail. This is error prone,
- and in the case of NULL pointers causes program termination (on
- many machines), if overlooked. Also, the code tends to be severely
- cluttered with tests for NULL.
-
- A better approach (IMHO) is to register errors in an error variable,
- which can be a global variable, or one per object (for member functions).
- The error variable must be explicitly read and reset, before proceeding.
- The iostream library uses this approach, guaranteeing that all operations
- on a stream are ignored until the error is fixed. The advantage is
- that it is OK to omit some error tests, several function calls may
- safely be made before testing for errors.
-
- Of course, true C++ exceptions is the superior alternative (:-).
-
- --
- --------------------------------------------------------------------------
- | Johan Bengtsson, Telia Research AB, Aurorum 6, S-951 75 Lulea, Sweden |
- | Johan.Bengtsson@lulea.trab.se; Voice:(+46)92075471; Fax:(+46)92075490 |
- --------------------------------------------------------------------------
-