Usenet comp.unix.osf.misc (1992-2004)
 help / color / mirror / Atom feed
From: Philip Staite <"pstaite "@ vnet.ibm.com>
Subject: Re: Strange thing about exceptions and destructors
Date: 1997/05/13	[thread overview]
Message-ID: <5l9vs0$q30$2@news.rchland.ibm.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)?

Try this version with "noisy" copy constructor and assignment operator.

#include <iostream.h>

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.



  parent reply	other threads:[~1997-05-13  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 ` Gene Thompson
1997-05-12  4:00 ` Allen Hadden
1997-05-12  4:00 ` Doug Harrison
1997-05-12  4:00 ` Partha Sinha
1997-05-13  4:00 ` Philip Staite [this message]
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