home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #19 / NN_1992_19.iso / spool / comp / lang / cplus / 12901 < prev    next >
Encoding:
Text File  |  1992-08-25  |  1.9 KB  |  59 lines

  1. Path: sparky!uunet!wupost!sdd.hp.com!uakari.primate.wisc.edu!ames!pacbell.com!well!johnrp
  2. From: johnrp@well.sf.ca.us (John Panzer)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: break/continue (was: Re: Tiny proposal for named loops.)
  5. Message-ID: <BtKuK7.n2G@well.sf.ca.us>
  6. Date: 26 Aug 92 06:12:07 GMT
  7. References: <1992Aug25.034553.575@frumious.uucp> <rmartin.714756719@thor> <1992Aug26.040955.593@frumious.uucp>
  8. Sender: news@well.sf.ca.us
  9. Organization: Whole Earth 'Lectronic Link
  10. Lines: 47
  11.  
  12. In article <1992Aug26.040955.593@frumious.uucp> uunet.ca!frumious!pat writes:
  13. >rmartin@thor.Rational.COM (Bob Martin) writes:
  14. >
  15. >|No, exceptions do not violate structure (IMHO).  The function which
  16. >|throws an exception never returns!  The calling code preserves its
  17. >|invariants.  The exception is caught by code which expects it, so its
  18. ...(deleted)
  19. >An error function that stops your program alters the control flow
  20. >in a nice, simple way.  By contrast, exceptions can have somewhat
  21. >non-intuitive effects.  Consider this function:
  22. >
  23. >   void foo() {
  24. >      char* p = new char[17];
  25. >      doSomething();
  26. >      delete [] p;
  27. >   };
  28. >
  29. >If doSomething() can throw an exception, then foo() has a memory leak!
  30.  
  31. If doSomething() calls exit(), the program still has a memory leak.
  32. (Usually the memory is reclaimed by the system so you don't notice,
  33. but try it with shared memory sometime...)  On the other hand,
  34. in the presence of exceptions you have at least two ways to plug
  35. the leak:
  36.  
  37.   void foo() {
  38.     char * p = new char[23];
  39.     try {doSomething();}
  40.     catch(...) {delete p; throw;}
  41.     delete p;
  42.   }
  43.  
  44. Or, make a "resource acquisition" class:
  45.  
  46.   template <class T> class HeapArray {
  47.   public:
  48.     HeapArray(size_t NumElems) {Ptr = new T[NumElems];}
  49.     ~HeapArray(void) {delete Ptr;}
  50.     T * Ptr;
  51.   };
  52.   void foo() {
  53.     HeapArray<char> p(5);
  54.     doSomething();
  55.   } // p is destructed whether or not exception is thrown.
  56.  
  57. John Panzer
  58. johnrp@well.sf.ca.us
  59.