TITLE: copied exceptions during throw SD: Shappir Dan (shappir@math.tau.ac.il) [...] > #include > class Exception { > int v; > public: > Exception() : v(0) { } > Exception(const Exception& e) : v(e.v+1) { } > void Print() const { cout << v << '\n'; } > }; > > void Proc() throw(Exception) > { > throw Exception(); > } > > main() > { > try { > Proc(); > } > catch (Exception e) { > e.Print(); > } > } > > When compiled with Watcom v10.0 on a PC, the output of the program > was '2' and when compiled with GNU C++ v2.4 on a Sun the output was '1'. > I then changed the catch instruction to: > > catch (Exception& e) { > > Compiled with Watcom the output of the program was now '1' and with > GNU C++ the output was '0'. This raised several questions: > > 1. Does catching a reference to an object always produce fewer > object copy operations? SR: shekar@CS.MsState.edu, 25 Mar 96 Setting aside the difference between the actual numbers produced by the two compilers, the answer to the question is yes. Catching a reference to an object always produces fewer copy operations - just like passing function parameters. However, the major difference is irrespective of the way you catch an exception (value or reference), a copy of the exception is _always_ made during 'throw'. After that, 'catch' receives a reference of the copy if you catch by reference or a copy of the copy if you catch by value. Therefore, the output produced by Watcom compiler sounds more reasonable. OTOH, the GNU compiler might be optimizing away some of the copy operations. (BTW, I thought g++ supported exceptions only from v2.7.*. no?) SD: > 2. Is it always legal to catch a reference rather than an object? SR: Yes. It is legal AND preferable to catch a reference so that the 'catch' can take advantage when polymorphic objects are thrown. SD: > 3. If the answers to 1 and 2 are yes, then why not always catch a reference? > (most examples of exception handling that I've encountered were not > implemented in this way) SR: Yes. Always catch a reference. Probably the examples you have seen overlooked at least the comment on 2 above. [ I have Scott Meyer's "More Effective C++", a follow on to his first. It has a detailed discussion about the costs of throwing and using exceptions in your code. Highly recommended. -adc ]