Usenet comp.unix.osf.misc (1992-2004)
 help / color / mirror / Atom feed
From: Allen Hadden <ahadden@taratec.com>
To: Aleksandar Milivojevic <alex@srce.hr>
Subject: Re: Strange thing about exceptions and destructors
Date: 1997/05/12	[thread overview]
Message-ID: <337780B1.217E@taratec.com> (raw)
In-Reply-To: gl7mh4mt4y.fsf@bjesomar.srce.hr


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 <iostream.h>
> 
> 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



  parent reply	other threads:[~1997-05-12  4:00 UTC|newest]

Thread overview: 7+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
1997-05-12  4:00 Strange thing about exceptions and destructors Aleksandar Milivojevic
1997-05-12  4:00 ` Doug Harrison
1997-05-12  4:00 ` Allen Hadden [this message]
1997-05-12  4:00 ` Gene Thompson
1997-05-12  4:00 ` Partha Sinha
1997-05-13  4:00 ` Philip Staite
1997-05-14  4:00 ` Aleksandar Milivojevic
read-only archive

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox