home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!pipex!warwick!bham!bhamvx!mccauleyba
- From: mccauleyba@vax1.bham.ac.uk (Brian McCauley)
- Subject: Re: How to run destructors of all objects when failure exit occurs ?
- Sender: usenet@rs6000.bham.ac.uk (USENET News Service)
- Message-ID: <1992Nov16.131839.1@vax1.bham.ac.uk>
- Date: Mon, 16 Nov 1992 13:18:39 GMT
- Lines: 39
- References: <AAAsb0h8xN@inpbox.inp.nsk.su> <BxsFJE.6GL@news.cso.uiuc.edu>
- Organization: University of Birmingham
-
- In article <BxsFJE.6GL@news.cso.uiuc.edu>, pl2440@meibm31.cen.uiuc.edu (Paul Jay Lucas) writes:
- > In <AAAsb0h8xN@inpbox.inp.nsk.su> dolgov@inpbox.inp.nsk.su (Yuri V. Dolgov) writes:
- >
- >> Often I use failure program exit when some conditions are bad.
- >>The trouble is: I created some objects (e.g. dialog boxes, network connections
- >>and so on) and I want to run destructors before program exit.
- >>Is there exist standard technique in C++ language to solve this problem ?
- >
- > No; only statically-allocated objects are destroyed. Off the
- > top of my head, *a* way to have auto-objects destroyed would be
- > to make them register themselves with some global list of
- > objects on construction and deregister themselves on
- > destruction. Now, when the global "clean-up" object gets
- > destroyed, it could destroy all objects that are still
- > registered.
- >
- > Actually, they can't be auto objects, but must instead be
- > dynamically-allocated objects; it is illegal to delete anything
- > not allocated by new (as auto objects aren't).
- If you use exception handling rather than exit() then all your `auto's are
- destroyed neatly. To get rid of dynamics either have a global list (as above)
- or if you prefer an abitary number of `auto' "clean-up" objects each of
- which cleans up objects in a given scope. See the section in "The C++
- Prog.Lang.Edn.2" on exceptions for some examples of this.
-
- #define exit(i) throw int(i)
- int main() { try {/* program body */} catch (int retval) { return retval; } }
-
- Actually I wouldn't `#define exit' in reality but it shows the idea
-
- If, like me, your compiler does not yet have exception handling :-( then lobby
- your compiler implementor.
- --
- \\ ( ) No Bullshit! | Email: B.A.McCauley@bham.ac.uk
- . _\\__[oo from | Voice: +44 21 471 3789 (home)
- .__/ \\ /\@ /~) /~[ /\/[ | Fax: +44 21 625 2175 (work)
- . l___\\ /~~) /~~[ / [ | Snail: 197 Harborne Lane,
- # ll l\\ ~~~~ ~ ~ ~ ~ | Birmingham, B29 6SS, UK
- ###LL LL\\ (Brian McCauley) | ICBM: 52.5N 1.9W
-