home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!wupost!sdd.hp.com!uakari.primate.wisc.edu!ames!pacbell.com!well!johnrp
- From: johnrp@well.sf.ca.us (John Panzer)
- Newsgroups: comp.lang.c++
- Subject: Re: break/continue (was: Re: Tiny proposal for named loops.)
- Message-ID: <BtKuK7.n2G@well.sf.ca.us>
- Date: 26 Aug 92 06:12:07 GMT
- References: <1992Aug25.034553.575@frumious.uucp> <rmartin.714756719@thor> <1992Aug26.040955.593@frumious.uucp>
- Sender: news@well.sf.ca.us
- Organization: Whole Earth 'Lectronic Link
- Lines: 47
-
- In article <1992Aug26.040955.593@frumious.uucp> uunet.ca!frumious!pat writes:
- >rmartin@thor.Rational.COM (Bob Martin) writes:
- >
- >|No, exceptions do not violate structure (IMHO). The function which
- >|throws an exception never returns! The calling code preserves its
- >|invariants. The exception is caught by code which expects it, so its
- ...(deleted)
- >An error function that stops your program alters the control flow
- >in a nice, simple way. By contrast, exceptions can have somewhat
- >non-intuitive effects. Consider this function:
- >
- > void foo() {
- > char* p = new char[17];
- > doSomething();
- > delete [] p;
- > };
- >
- >If doSomething() can throw an exception, then foo() has a memory leak!
-
- If doSomething() calls exit(), the program still has a memory leak.
- (Usually the memory is reclaimed by the system so you don't notice,
- but try it with shared memory sometime...) On the other hand,
- in the presence of exceptions you have at least two ways to plug
- the leak:
-
- void foo() {
- char * p = new char[23];
- try {doSomething();}
- catch(...) {delete p; throw;}
- delete p;
- }
-
- Or, make a "resource acquisition" class:
-
- template <class T> class HeapArray {
- public:
- HeapArray(size_t NumElems) {Ptr = new T[NumElems];}
- ~HeapArray(void) {delete Ptr;}
- T * Ptr;
- };
- void foo() {
- HeapArray<char> p(5);
- doSomething();
- } // p is destructed whether or not exception is thrown.
-
- John Panzer
- johnrp@well.sf.ca.us
-