From mboxrd@z Thu Jan 1 00:00:00 1970 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: fee84,d57b97ad32cb5f46 X-Google-Attributes: gidfee84,public X-Google-Thread: 10ba33,d57b97ad32cb5f46 X-Google-Attributes: gid10ba33,public X-Google-Thread: 11035d,d57b97ad32cb5f46 X-Google-Attributes: gid11035d,public X-Google-Thread: 109fba,d57b97ad32cb5f46 X-Google-Attributes: gid109fba,public X-Google-Thread: f678f,d57b97ad32cb5f46 X-Google-Attributes: gidf678f,public From: Philip Staite <"pstaite "@ vnet.ibm.com> Subject: Re: Strange thing about exceptions and destructors Date: 1997/05/13 Message-ID: <5l9vs0$q30$2@news.rchland.ibm.com>#1/1 X-Deja-AN: 241303771 Distribution: inet References: Organization: IBM Rochester MN http://www.ibm.com/ Newsgroups: comp.lang.c++,comp.unix.osf.misc,comp.unix.osf.osf1,comp.unix.solaris,gnu.g++.help Aleksandar Milivojevic wrote: > > I would like to know when the destructor for thrown object is called. I > expected that it is called only one time (and not two or three times) > after the catch block is executed. So in order to check that, I wrote > a simple program and it gave me three different outputs when compiled > with Sun CC, DEC cxx and GNU g++ (last gave me internal compiler > error, but when I commented last line of main() it compiled OK). > > Now, Am I doing something totaly wrong, or that three compilers > generate incorect code (and which one generated correct code, if any)? Try this version with "noisy" copy constructor and assignment operator. #include class exp { public: exp( int x ) : i( x ) { cout << "ctor -- " << *this << endl; } ~exp() { cout << "dtor -- " << *this << endl; } exp( const exp& e ) : i( e.i ) { cout << "copy ctor -- " << *this << " from " << e << endl; } exp& operator=( const exp& e ) { cout << "assignment " << *this << " = " << e << endl; if( &e != this ) i = e.i; return *this; } friend ostream& operator<<( ostream& o, const exp& e ) { return o << "exp{" << e.i << "} at: " << &e; } private: int i; }; main() { try { cout << "Throwing exception\n"; throw exp(1); } catch (exp a) { cout << "Caught " << a << endl; } cout << "Exiting\n"; } When compiled with xlC on AIX I get: ~> a.out Throwing exception ctor -- exp{1} at: 0x2ff220f0 copy ctor -- exp{1} at: 0x2ff220f8 from exp{1} at: 0x2ff220f0 Caught exp{1} at: 0x2ff220f8 dtor -- exp{1} at: 0x2ff220f8 dtor -- exp{1} at: 0x2ff220f0 Exiting ~> -- Phil Staite If I were an IBM spokesperson I'd have pstaite @ vnet.ibm.com business cards, not disclaimers.