home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #27 / NN_1992_27.iso / spool / comp / lang / cplus / 16509 < prev    next >
Encoding:
Internet Message Format  |  1992-11-18  |  2.4 KB

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