Exceptions : Something I'm missing ?[SOLVED]

Started by
6 comments, last by Mocanu Razvan 18 years, 1 month ago
Hi. I am now studying exceptions in C++. I wrote code to test destruction of thrown exception objects and when they occur. The output is somewhat strange. Here is the code:

class X {
public:
	class XExc {
	public:
		XExc() { cout << "Constructor X::XExc" << endl; }
//              XExc(const XExc&) { cout << "Copy X::XExc" << endl; }
		~XExc() { cout << "Destuctor X::XExc" << endl; }
	};
	void f() { 
		cout << "Inside f" << endl;
		throw XExc(); }
};

int main() {
	X x;
	try {
		x.f();
	} catch(X::XExc&) {
		cout << "Exception handler" << endl;
	}
}



The output is : Inside f Constructor X::XExc Destuctor X::XExc Exception handler Destuctor X::XExc So the first destructor destroys the original XExc and the second destroys the copy made when throw is encountered.(at least that's how i see it) But, notice I commented the copy-constructor. If I explicitly specify one, there's no Destructor before the handler, but there's no copy constructor output either. I am a little confused here. [Edited by - Mocanu Razvan on April 14, 2006 4:29:41 AM]
-= wolfwood :: rpg =-
Advertisement
Someone please correct me if I am wrong but I am not sure you should be catching a reference like that.
Quote:Original post by EasilyConfused
Someone please correct me if I am wrong but I am not sure you should be catching a reference like that.


Why not? Though you should probably catch it as const reference...

To the OP: It seems like it's able to optimize away the temporary when the copy constructor is user-defined. Not sure exactly why it won't optimize it when it's compiler-generated...
Throw by value, catch by reference.

I come to the same conclusion as RDragon. You might try making your example a little less contrived (throw from a deeper point, so more unwinding occurs, give your class some actual data to copy, et cetera) and see how things change.
Quote:Original post by RDragon1
To the OP: It seems like it's able to optimize away the temporary when the copy constructor is user-defined. Not sure exactly why it won't optimize it when it's compiler-generated...


Perhaps it's because he is compiling without optimizations? When run in "Release" mode in VC++2005, it behaves "correctly".


jfl.
Makes sense. Duh ;)
It's up to the compiler how many times the object gets copied.
Yes indeed. I forgot I was using the Debug configuration. Compiling in Release mode solves the problem. And yes, it seems to be optimizing away the temporary.

Thanks.
-= wolfwood :: rpg =-

This topic is closed to new replies.

Advertisement