From mboxrd@z Thu Jan 1 00:00:00 1970 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 109fba,d57b97ad32cb5f46 X-Google-Attributes: gid109fba,public X-Google-Thread: f678f,d57b97ad32cb5f46 X-Google-Attributes: gidf678f,public X-Google-Thread: 10ba33,d57b97ad32cb5f46 X-Google-Attributes: gid10ba33,public X-Google-Thread: fee84,d57b97ad32cb5f46 X-Google-Attributes: gidfee84,public X-Google-Thread: 11035d,d57b97ad32cb5f46 X-Google-Attributes: gid11035d,public From: Allen Hadden Subject: Re: Strange thing about exceptions and destructors Date: 1997/05/12 Message-ID: <337780B1.217E@taratec.com>#1/1 X-Deja-AN: 241371176 References: To: Aleksandar Milivojevic Organization: Taratec Development Corp Reply-To: ahadden@taratec.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)? > > Here is program, and the outputs it gives when compiled with before > mentioned compilers: > > #include > > class exp { > public: > exp(int x); > ~exp(); > int i; > }; > > exp::exp(int x) { > cout << "Constructor exp(" << x << ")\n"; > i = x; > } > > exp::~exp() { > cout << "Destructor ~exp()\n"; > } > > main() { > try { > cout << "Throwing exception\n"; > throw exp(1); > } catch (exp a) { > cout << "Catched exp(" << a.i << ")\n"; > } > cout << "Exiting\n"; > } > Not sure why they are giving such different results. A copy of the thrown exp is getting created. If you add a copy constructor for exp and put some debug code there, you may be able to see what is going on. exp( const exp& copy ) { // Perform the copy i = copy.i; cout << "Copy constructor" << endl; } Also, you should probably not catch by value. Try catching by reference instead: main() { try { cout << "Throwing exception\n"; throw exp(1); } catch (exp& a) { cout << "Catched exp(" << a.i << ")\n"; } cout << "Exiting\n"; } -Allen -- Allen Hadden Systems Engineer/Laboratory Application Specialist Taratec Development Corporation ahadden@taratec.com